Start anew
[git/jnareb-git.git] / share / vim / vim58 / doc / autocmd.txt
blobb5da5080302e2d407c75479c7536dbe76c757547
1 *autocmd.txt*   For Vim version 5.8.  Last change: 2001 Feb 01
4                   VIM REFERENCE MANUAL    by Bram Moolenaar
7 Automatic commands                                      *autocommand*
9 1.  Introduction                |autocmd-intro|
10 2.  Defining autocommands       |autocmd-define|
11 3.  Removing autocommands       |autocmd-remove|
12 4.  Listing autocommands        |autocmd-list|
13 5.  Events                      |autocmd-events|
14 6.  Patterns                    |autocmd-patterns|
15 7.  Filetypes                   |autocmd-filetypes|
16 8.  Groups                      |autocmd-groups|
17 9.  Executing autocommands      |autocmd-execute|
18 10. Using autocommands          |autocmd-use|
20 {Vi does not have any of these commands}
22 ==============================================================================
23 1. Introduction                                         *autocmd-intro*
25 You can specify commands to be executed automatically for when reading or
26 writing a file, when entering or leaving a buffer or window, and when exiting
27 Vim.  For example, you can create an autocommand to set the 'cindent' option
28 for files matching *.c.  You can also use autocommands to implement advanced
29 features, such as editing compressed files (see |gzip-example|).  The usual
30 place to put autocommands is in your .vimrc or .exrc file.
32 WARNING: Using autocommands is very powerful, and may lead to unexpected side
33 effects.  Be careful not to destroy your text.
34 - It's a good idea to do some testing on an expendable copy of a file first.
35   For example: If you use autocommands to decompress a file when starting to
36   edit it, make sure that the autocommands for compressing when writing work
37   correctly.
38 - Be prepared for an error halfway through (e.g., disk full).  Vim will mostly
39   be able to undo the changes to the buffer, but you may have to clean up the
40   changes to other files by hand (e.g., compress a file that has been
41   decompressed).
42 - If the BufRead* events allow you to edit a compressed file, the FileRead*
43   events should do the same (this makes recovery possible in some rare cases).
44   It's a good idea to use the same autocommands for the File* and Buf* events
45   when possible.
47 The |+autocmd| feature is only included if it has not been disabled at compile
48 time.
50 ==============================================================================
51 2. Defining autocommands                                *autocmd-define*
53 Note: The ":autocmd" command cannot be followed by another command, since any
54 '|' is considered part of the command.
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].
65 Note that special characters (e.g., "%", "<cword>") in the ":autocmd"
66 arguments are not expanded when the autocommand is defined.  These will be
67 expanded when the Event is recognized, and the {cmd} is executed.  The only
68 exception is that "<sfile>" is expanded when the autocmd is defined.  Example:
70 >       :au BufNewFile,BufRead *.html so <sfile>:h/html.vim
72 Here Vim expands <sfile> to the name of the file containing this line.
74 When your .vimrc file is sourced twice, the autocommands will appear twice.
75 To avoid this, put this command in your .vimrc file, before defining
76 autocommands:
78 >       :autocmd!       " Remove ALL autocommands.
80 If you don't want to remove all autocommands, you can instead use a variable
81 to ensure that Vim includes the autocommands only once:
83 >       :if !exists("autocommands_loaded")
84 >       :  let autocommands_loaded = 1
85 >       :  au ...
86 >       :endif
88 When the [group] argument is not given, Vim uses the current group (as defined
89 with ":augroup"); otherwise, Vim uses the group defined with [group].  Note
90 that [group] must have been defined before.  You cannot define a new group
91 with ":au group ..."; use ":augroup" for that.
93 While testing autocommands, you might find the 'verbose' option to be useful:
94 >       :set verbose=9
95 This setting makes Vim echo the autocommands as it executes them.
97 ==============================================================================
98 3. Removing autocommands                                *autocmd-remove*
100 :au[tocmd]! [group] {event} {pat} [nested] {cmd}
101                         Remove all autocommands associated with {event} and
102                         {pat}, and add the command {cmd}.  See
103                         |autocmd-nested| for [nested].
105 :au[tocmd]! [group] {event} {pat}
106                         Remove all autocommands associated with {event} and
107                         {pat}.
109 :au[tocmd]! [group] * {pat}
110                         Remove all autocommands associated with {pat} for all
111                         events.
113 :au[tocmd]! [group] {event}
114                         Remove ALL autocommands for {event}.
116 :au[tocmd]! [group]     Remove ALL autocommands.
118 When the [group] argument is not given, Vim uses the current group (as defined
119 with ":augroup"); otherwise, Vim uses the group defined with [group].
121 ==============================================================================
122 4. Listing autocommands                                 *autocmd-list*
124 :au[tocmd] [group] {event} {pat}
125                         Show the autocommands associated with {event} and
126                         {pat}.
128 :au[tocmd] [group] * {pat}
129                         Show the autocommands associated with {pat} for all
130                         events.
132 :au[tocmd] [group] {event}
133                         Show all autocommands for {event}.
135 :au[tocmd] [group]      Show all autocommands.
137 If you provide the [group] argument, Vim lists only the autocommands for
138 [group]; otherwise, Vim lists the autocommands for ALL groups.  Note that this
139 argument behavior differs from that for defining and removing autocommands.
141 ==============================================================================
142 5. Events                                               *autocmd-events*
144                                         *autocommand-events* *{event}*
145 Vim recognizes the following events.  Vim ignores the case of event names
146 (e.g., you can use "BUFread" or "bufread" instead of "BufRead").
148                                                         *BufNewFile*
149 BufNewFile                      When starting to edit a file that doesn't
150                                 exist.  Can be used to read in a skeleton
151                                 file.
152                                                         *BufReadPre*
153 BufReadPre                      When starting to edit a new buffer, before
154                                 reading the file into the buffer.  Not used
155                                 if the file doesn't exist.
156                                                 *BufRead* *BufReadPost*
157 BufRead or BufReadPost          When starting to edit a new buffer, after
158                                 reading the file into the buffer, before
159                                 executing the modelines.  This does NOT work
160                                 for ":r file".  Not used when the file doesn't
161                                 exist.  Also used after successfully recovering
162                                 a file.
163                                                         *BufFilePre*
164 BufFilePre                      Before changing the name of the current buffer
165                                 with the ":file" command.
166                                                         *BufFilePost*
167 BufFilePost                     After changing the name of the current buffer
168                                 with the ":file" command.
169                                                         *FileReadPre*
170 FileReadPre                     Before reading a file with a ":read" command.
171                                                         *FileReadPost*
172 FileReadPost                    After reading a file with a ":read" command.
173                                 Note that Vim sets the '[ and '] marks to the
174                                 first and last line of the read.  This can be
175                                 used to operate on the lines just read.
176                                                         *FilterReadPre*
177 FilterReadPre                   Before reading a file from a filter command.
178                                 Vim checks the pattern against the name of
179                                 the current buffer, not the name of the
180                                 temporary file that is the output of the
181                                 filter command.
182                                                         *FilterReadPost*
183 FilterReadPost                  After reading a file from a filter command.
184                                 Vim checks the pattern against the name of
185                                 the current buffer as with FilterReadPre.
186                                                         *FileType*
187 FileType                        When the 'filetype' option has been set.
188                                 <afile> can be used for the name of the file
189                                 where this option was set, and <amatch> for
190                                 the new value of 'filetype'.
191                                 See |autocmd-filetypes|.
192                                                         *Syntax*
193 Syntax                          When the 'syntax' option has been set.
194                                 <afile> can be used for the name of the file
195                                 where this option was set, and <amatch> for
196                                 the new value of 'syntax'.
197                                 See |:syn-on|.
198                                                         *StdinReadPre*
199 StdinReadPre                    Before reading from stdin into the buffer.
200                                 Only used when the "-" argument was used when
201                                 Vim was started |--|.
202                                                         *StdinReadPost*
203 StdinReadPost                   After reading from the stdin into the buffer,
204                                 before executing the modelines.  Only used
205                                 when the "-" argument was used when Vim was
206                                 started |--|.
207                                                 *BufWrite* *BufWritePre*
208 BufWrite or BufWritePre         Before writing the whole buffer to a file.
209                                                         *BufWritePost*
210 BufWritePost                    After writing the whole buffer to a file
211                                 (should undo the commands for BufWritePre).
212                                                         *FileWritePre*
213 FileWritePre                    Before writing to a file, when not writing the
214                                 whole buffer.
215                                                         *FileWritePost*
216 FileWritePost                   After writing to a file, when not writing the
217                                 whole buffer.
218                                                         *FileAppendPre*
219 FileAppendPre                   Before appending to a file.
220                                                         *FileAppendPost*
221 FileAppendPost                  After appending to a file.
222                                                         *FilterWritePre*
223 FilterWritePre                  Before writing a file for a filter command.
224                                 Vim checks the pattern against the name of
225                                 the current buffer, not the name of the
226                                 temporary file that is the output of the
227                                 filter command.
228                                                         *FilterWritePost*
229 FilterWritePost                 After writing a file for a filter command.
230                                 Vim checks the pattern against the name of
231                                 the current buffer as with FilterWritePre.
232                                                         *FileChangedShell*
233 FileChangedShell                After Vim runs a shell command and notices
234                                 that the modification time of a file has
235                                 changed since editing started.  This
236                                 autocommand is triggered for each changed
237                                 file.  Run in place of the 'has been changed'
238                                 message.  See |timestamp|.  Useful for
239                                 reloading related buffers which are affected
240                                 by a single command.
241                                 NOTE: When this autocommand is executed, the
242                                 current buffer "%" may be different from the
243                                 buffer that was changed "<afile>".
244                                 NOTE: This even never nests, to avoid an
245                                 endless loop.
246                                                         *FocusGained*
247 FocusGained                     When Vim got input focus.  Only for the GUI
248                                 version and a few console versions where this
249                                 can be detected.
250                                                         *FocusLost*
251 FocusLost                       When Vim lost input focus.  Only for the GUI
252                                 version and a few console versions where this
253                                 can be detected.
254                                                         *CursorHold*
255 CursorHold                      When the user doesn't press a key for the time
256                                 specified with 'updatetime'.  Not re-triggered
257                                 until the user has pressed a key (i.e. doesn't
258                                 fire every 'updatetime' ms if you leave Vim to
259                                 make some coffee. :)  See |CursorHold-example|
260                                 for previewing tags.
261                                 Note: Interactive commands and ":normal"
262                                 cannot be used for this event.
263                                 Note: In the future there will probably be
264                                 another option to set the time.
265                                 {only on Amiga, Unix, Win32, MSDOS and all GUI
266                                 versions}
267                                                         *BufEnter*
268 BufEnter                        After entering a buffer.  Useful for setting
269                                 options for a file type.  Also executed when
270                                 starting to edit a buffer, after the
271                                 BufReadPost autocommands.
272                                                         *BufLeave*
273 BufLeave                        Before leaving to another buffer.  Also when
274                                 leaving or closing the current window and the
275                                 new current window is not for the same buffer.
276                                 Not used for ":qa" or ":q" when exiting Vim.
277                                                         *BufUnload*
278 BufUnload                       Before unloading a buffer.  This is when the
279                                 text in the buffer is going to be freed.  This
280                                 may be after a BufWritePost and before a
281                                 BufDelete.  NOTE: When this autocommand is
282                                 executed, the current buffer "%" may be
283                                 different from the buffer being unloaded
284                                 "<afile>".
285                                                         *BufHidden*
286 BufHidden                       Just after a buffer has become hidden.  That
287                                 is, when there are no longer windows that show
288                                 the buffer, but the buffer is not unloaded or
289                                 deleted.  NOTE: When this autocommand is
290                                 executed, the current buffer "%" may be
291                                 different from the buffer being unloaded
292                                 "<afile>".
293                                                         *BufCreate*
294 BufCreate                       Just after creating a new buffer.  Also used
295                                 just after a buffer has been renamed.  NOTE:
296                                 When this autocommand is executed, the current
297                                 buffer "%" may be different from the buffer
298                                 being deleted "<afile>".
299                                                         *BufDelete*
300 BufDelete                       Before deleting a buffer from the buffer list.
301                                 The BufUnload may be called first (if the
302                                 buffer was loaded).  Also used just before a
303                                 buffer is renamed.  NOTE: When this
304                                 autocommand is executed, the current buffer
305                                 "%" may be different from the buffer being
306                                 deleted "<afile>".
307                                                         *WinEnter*
308 WinEnter                        After entering another window.  Not done for
309                                 the first window, when Vim has just started.
310                                 Useful for setting the window height.
311                                 If the window is for another buffer, Vim
312                                 executes the BufEnter autocommands after the
313                                 WinEnter autocommands.
314                                                         *WinLeave*
315 WinLeave                        Before leaving a window.  If the window to be
316                                 entered next is for a different buffer, Vim
317                                 executes the BufLeave autocommands before the
318                                 WinLeave autocommands (but not for ":new").
319                                 Not used for ":qa" or ":q" when exiting Vim.
320                                                         *GUIEnter*
321 GUIEnter                        After starting the GUI succesfully, and after
322                                 opening the window.  It is triggered before
323                                 VimEnter when using gvim.  Can be used to
324                                 position the window from a .gvimrc file:
325 >       :autocommand GUIEnter * winpos 100 50
326                                                         *VimEnter*
327 VimEnter                        After doing all the startup stuff, including
328                                 loading .vimrc files, executing the "-c cmd"
329                                 arguments, creating all windows and loading
330                                 the buffers in them.
331                                                         *VimLeavePre*
332 VimLeavePre                     Before exiting Vim, just before writing the
333                                 .viminfo file.  This is executed only once,
334                                 if there is a match with the name of what
335                                 happens to be the current buffer when exiting.
336                                 Mostly useful with a "*" pattern.
337 >       :autocmd VimLeavePre * call CleanupStuff()
338                                                         *VimLeave*
339 VimLeave                        Before exiting Vim, just after writing the
340                                 .viminfo file.  Executed only once, like
341                                 VimLeavePre.
342                                                         *FileEncoding*
343 FileEncoding                    Fires off when you change the file encoding
344                                 with ':set fileencoding'.  Allows you to set
345                                 up fonts or other language sensitive settings.
346                                                         *TermChanged*
347 TermChanged                     After the value of 'term' has changed.  Useful
348                                 for re-loading the syntax file to update the
349                                 colors, fonts and other terminal-dependent
350                                 settings.  Executed for all loaded buffers.
351                                                         *User*
352 User                            Never executed automatically.  To be used for
353                                 autocommands that are only executed with
354                                 ":doautocmd".
357 For READING FILES there are three possible pairs of events.  Vim uses only one
358 pair at a time:
359 BufNewFile                      starting to edit a non-existent file
360 BufReadPre      BufReadPost     starting to edit an existing file
361 FilterReadPre   FilterReadPost  read the temp file with filter output
362 FileReadPre     FileReadPost    any other file read
364 Note that the autocommands for the *ReadPre events and all the Filter events
365 are not allowed to change the current buffer (you will get an error message if
366 this happens).  This is to prevent the file to be read into the wrong buffer.
368 Note that the 'modified' flag is reset AFTER executing the BufReadPost
369 and BufNewFile autocommands.  But when the 'modified' option was set by the
370 autocommands, this doesn't happen.
372 You can use the 'eventignore' option to ignore a number of events or all
373 events.
375 ==============================================================================
376 6. Patterns                                             *autocmd-patterns*
378 The file pattern {pat} is tested for a match against the file name in one of
379 two ways:
380 1. When there is no '/' in the pattern, Vim checks for a match against only
381    the tail part of the file name (without its leading directory path).
382 2. When there is a '/' in the pattern,  Vim checks for a match against the
383    both short file name (as you typed it) and the full file name (after
384    expanding it to a full path and resolving symbolic links).
386 Examples:
387 >       :autocmd BufRead *.txt          set et
388 Set the 'et' option for all text files.
390 >       :autocmd BufRead /vim/src/*.c   set cindent
391 Set the 'cindent' option for C files in the /vim/src directory.
393 >       :autocmd BufRead /tmp/*.c       set ts=5
394 If you have a link from "/tmp/test.c" to "/home/nobody/vim/src/test.c", and
395 you start editing "/tmp/test.c", this autocommand will match.
397 Note:  To match part of a path, but not from the root directory, use a '*' as
398 the first character.  Example:
399 >       :autocmd BufRead */doc/*.txt    set tw=78
400 This autocommand will for example be executed for "/tmp/doc/xx.txt" and
401 "/usr/home/piet/doc/yy.txt".  The number of directories does not matter here.
404 Environment variables can be used in a pattern:
405 >       :autocmd BufRead $VIMRUNTIME/doc/*.txt  set expandtab
406 And ~ can be used for the home directory (if $HOME is defined):
407 >       :autocmd BufWritePost ~/.vimrc   so ~/.vimrc
408 >       :autocmd BufRead ~archive/*      set readonly
409 The environment variable is expanded when the autocommand is defined, not when
410 the autocommand is executed.  This is different from the command!
412 The pattern is interpreted like mostly used in file names:
413         *       matches any sequence of characters
414         ?       matches any single character
415         \?      matches a '?'
416         .       matches a '.'
417         ~       matches a '~'
418         ,       separates patterns
419         \,      matches a ','
420         { }     like \( \) in a |pattern|
421         ,       inside { }: like \| in a |pattern|
422         \       special meaning like in a |pattern|
423         [ch]    matches 'c' or 'h'
425 Note that for all systems the '/' character is used for path separator (even
426 MS-DOS and OS/2).  This was done because the backslash is difficult to use
427 in a pattern and to make the autocommands portable across different systems.
429 ==============================================================================
430 7. Filetypes                                            *autocmd-filetypes*
432 Vim can detect the type of file that is edited.  This is done by checking the
433 file name and sometimes by inspecting the contents of the file for specific
434 text.
436                                                         *:filetype* *:filet*
437 To enable file type detection, use this command in your vimrc:
438 >  :filetype on
439 Each time a new or existing file is edited, Vim will try to recognize the type
440 of the file and set the 'filetype' option.  This will trigger the FileType
441 event, which can be used to set the syntax highlighting, set options, etc.
443 Detail: The ":filetype on" command will load the file
444         $VIMRUNTIME/filetype.vim, which defines autocommands for the
445         BufNewFile and BufRead events.  If the file type is not found by the
446         name, the file $VIMRUNTIME/scripts.vim is used to detect it from the
447         contents of the file.
449 To add your own file types, see |new-filetype| below.
451 If the file type is not detected automatically, or it finds the wrong type,
452 you can either set the 'filetype' option manually, or add a modeline to your
453 file.  Example, for in an IDL file use the command:
454 >       set filetype=idl
455 or add this |modeline| to the file:
456 >       /* vim: set filetype=idl : */
458 You can use the detected file type to set options and install mappings.  For
459 example, to set the 'tabstop' option for C files to 4:
460 >  :autocmd FileType c          set tabstop=4
462 Example to install a mapping for Java:
463 >  :autocmd FileType java       map <F4> /import<CR>
465 NOTE: Although a mapping is installed for a specific file type, it will be
466 used for all buffers.  There are no mappings local to a buffer yet.
468 If you have several commands to be executed, it is more convenient to put them
469 in a function.  This is faster and more easy to maintain.  Example:
470 >  autocmd FileType cpp         call FT_cpp()
471 >  function FT_cpp()
472 >    map <F4> a#include ""<Esc>i
473 >    set cindent shiftwidth=4 softtabstop=4
474 >  endfunction
476 The file types are also used for syntax highlighting.  If the ":syntax on"
477 command is used, the file type detection is installed too.  There is no need
478 to do ":filetype on" after ":syntax on".
480 To disable file type detection, use this command:
481 >  :filetype off
483 To disable one of the file types, add a line in the myfiletypefile, see
484 |remove-filetype|.
486                                                         *new-filetype*
487 If a file type that you want to use is not detected yet, there are two ways to
488 add it.  It's better not modify the $VIMRUNTIME/filetype.vim file.  It will be
489 overwritten when installing a new version of Vim.
491                                                         *myfiletypefile*
492 1. If your file type can be detected by the file name.
493    Create a file that contains autocommands to detect the file type.
494    Example:
495 >    " myfiletypefile
496 >    augroup filetype
497 >      au! BufRead,BufNewFile *.mine    set filetype=mine
498 >      au! BufRead,BufNewFile *.xyz     set filetype=drawing
499 >    augroup END
501    Then add a line in your vimrc file to set the "myfiletypefile" variable to
502    the name of this file.  Example:
503 >    let myfiletypefile = "~/vim/myfiletypes.vim"
505    Your file will then be sourced after the default FileType autocommands have
506    been installed.  This allows you to overrule any of the defaults, by using
507    ":au!" to remove any existing FileType autocommands for the same pattern.
508    Only the autocommand to source the scripts.vim file is given later.  This
509    makes sure that your autocommands in "myfiletypefile" are used before
510    checking the contents of the file.
512    NOTE: Make sure that you set "myfiletypefile" before switching on file type
513    detection.  Thus is must be before any ":filetype on" or ":syntax on"
514    command.
516                                                         *myscriptsfile*
517 2. If your file type can only be detected by inspecting the contents of the
518    file, create a vim script file for doing this.  Example:
519 >     if getline(1) =~ '^#!.*\<mine\>'
520 >       set filetype= mine
521 >     endif
522    See $VIMRUNTIME/scripts.vim for more examples.
523    Let's assume you write this file in "~/vim/myscripts.vim".  Then set the
524    "myscriptsfile" variable to this file name.  Example:
525 >    let myscriptsfile = "~/vim/myscripts.vim"
526    The "myscriptsfile" is loaded in $VIMRUNTIME/scripts.vim before the default
527    checks for file types, which means that your rules override the default
528    rules in $VIMRUNTIME/scripts.vim.
530                                                 *remove-filetype*
531 If a file type is detected that is wrong for you, you can remove it by
532 deleting the autocommand that detects the file type.  This is best done by
533 adding a line in your |myfiletypefile|:
534 >       augroup filetype
535 >       au! BufNewFile,BufRead {pattern}
536 >       augroup END
537 Where {pattern} is the matched pattern that you want to be ignored.
539 If the file type is actually detected by a script, you need to avoid that
540 $VIMRUNTIME/scripts.vim does its work.  That can be done by setting 'filetype'
541 to an unrecognized name, for example "ignored":
542 >       augroup filetype
543 >       au! BufNewFile,BufRead {pattern} set ft=ignored
544 >       augroup END
546 If you are setting up a system with many users, and you don't want each user
547 to add/remove the same filetypes, consider creating a vimrc file that is used
548 for everybody.  See |system-vimrc|.
551                                                 *autocmd-osfiletypes*
552 On operating systems which support storing a file type with the file, you can
553 specify that an autocommand should only be executed if the file is of a
554 certain type.
556 The actual type checking depends on which platform you are running Vim
557 on; see your system's documentation for details.
559 To use osfiletype checking in an autocommand you should put a list of types to
560 match in angle brackets in place of a pattern, like this:
562 > :au BufRead *.html,<&faf;HTML>  so $VIMRUNTIME/syntax/html.vim
564 This will match:
566 - Any file whose name ends in `.html'
567 - Any file whose type is `&faf' or 'HTML', where the meaning of these types
568   depends on which version of Vim you are using.
569   Unknown types are considered NOT to match.
571 You can also specify a type and a pattern at the same time (in which case they
572 must both match):
574 > :au BufRead <&fff>diff*
576 This will match files of type `&fff' whose names start with `diff'.
578 Note that osfiletype checking is skipped if Vim is compiled without the
579 |+osfiletype| feature.
581 ==============================================================================
582 8. Groups                                               *autocmd-groups*
584 Autocommands can be put together in a group.  This is useful for removing or
585 executing a group of autocommands.  For example, all the autocommands for
586 syntax highlighting are put in the "highlight" group, to be able to execute
587 ":doautoall highlight BufRead" when the GUI starts.
589 When no specific group is selected, Vim uses the default group.  The default
590 group does not have a name.  You cannot execute the autocommands from the
591 default group separately; you can execute them only by executing autocommands
592 for all groups.
594 Normally, when executing autocommands automatically, Vim uses the autocommands
595 for all groups.  The group only matters when executing autocommands with
596 ":doautocmd" or ":doautoall", or when defining or deleting autocommands.
598 The group name can contain any characters except white space.  The group name
599 "end" is reserved (also in uppercase).  The group name is case sensitive.
601                                                         *:aug* *:augroup*
602 :aug[roup] {name}               Define the autocmd group name for the
603                                 following ":autocmd" commands.  The name "end"
604                                 or "END" selects the default group.
606 To enter autocommands for a specific group, use this method:
607 1. Select the group with ":augroup {name}".
608 2. Delete any old autocommands with ":au!".
609 3. Define the autocommands.
610 4. Go back to the default group with "augroup END".
612 Example:
613 >       :augroup uncompress
614 >       :  au!
615 >       :  au BufEnter *.gz     %!gunzip
616 >       :augroup END
618 This prevents having the autocommands defined twice (e.g., after sourcing the
619 .vimrc file again).
621 ==============================================================================
622 9. Executing autocommands                               *autocmd-execute*
624 Vim can also execute Autocommands non-automatically.  This is useful if you
625 have changed autocommands, or when Vim has executed the wrong autocommands
626 (e.g., the file pattern match was wrong).
628 Note that the 'eventignore' option applies here too.  Events listed in this
629 option will not cause any commands to be executed.
631                                                         *:do* *:doautocmd*
632 :do[autocmd] [group] {event} [fname]
633                         Apply the autocommands matching [fname] (default:
634                         current file name) for {event} to the current buffer.
635                         You can use this when the current file name does not
636                         match the right pattern, after changing settings, or
637                         to execute autocommands for a certain event.
638                         It's possible to use this inside an autocommand too,
639                         so you can base the autocommands for one extension on
640                         another extension.  Example:
641 >                               :au Bufenter *.cpp so ~/.vimrc_cpp
642 >                               :au Bufenter *.cpp doau BufEnter x.c
643                         Be careful to avoid endless loops.  See
644                         |autocmd-nested|.
646                         When the [group] argument is not given, Vim executes
647                         the autocommands for all groups.  When the [group]
648                         argument is included, Vim executes only the matching
649                         autocommands for that group.  Note: if you use an
650                         undefined group name, Vim gives you an error message.
652                                                 *:doautoa* *:doautoall*
653 :doautoa[ll] [group] {event} [fname]
654                         Like ":doautocmd", but apply the autocommands to each
655                         loaded buffer.  Careful: Don't use this for
656                         autocommands that delete a buffer, change to another
657                         buffer or change the contents of a buffer; the result
658                         is unpredictable.  this command is intended for
659                         autocommands that set options, change highlighting,
660                         and things like that.
662 ==============================================================================
663 10. Using autocommands                                  *autocmd-use*
665 For WRITING FILES there are four possible pairs of events.  Vim uses only one
666 pair at a time:
667 BufWritePre     BufWritePost    writing the whole buffer
668 FilterWritePre  FilterWritePost writing to the temp file with filter input
669 FileAppendPre   FileAppendPost  appending to a file
670 FileWritePre    FileWritePost   any other file write
672 Note that the *WritePost commands should undo any changes to the buffer that
673 were caused by the *WritePre commands; otherwise, writing the file will have
674 the side effect of changing the buffer.
676 Before executing the autocommands, the buffer from which the lines are to be
677 written temporarily becomes the current buffer.  Unless the autocommands
678 change the current buffer or delete the previously current buffer, the
679 previously current buffer is made the current buffer again.
681 The *WritePre and *AppendPre autocommands must not delete the buffer from
682 which the lines are to be written.
684 The '[ and '] marks have a special position:
685 - Before the *ReadPre event the '[ mark is set to the line just above where
686   the new lines will be inserted.
687 - Before the *ReadPost event the '[ mark is set to the first line that was
688   just read, the '] mark to the last line.
689 - Before executing the *WritePre and *AppendPre autocommands the '[ mark is
690   set to the first line that will be written, the '] mark to the last line.
691 Careful: '[ and '] change when using commands that change the buffer.
693 In commands which expect a file name, you can use "<afile>" for the file name
694 that is being read |:<afile>| (you can also use "%" for the current file
695 name).  "<abuf>" can be used for the buffer number of the currently effective
696 buffer.  This also works for buffers that doesn't have a name.  But it doesn't
697 work for files without a buffer (e.g., with ":r file").
699                                                         *gzip-example*
700 Examples for reading and writing compressed files:
701 > :augroup gzip
702 > :  autocmd!
703 > :  autocmd BufReadPre,FileReadPre     *.gz set bin
704 > :  autocmd BufReadPost,FileReadPost   *.gz '[,']!gunzip
705 > :  autocmd BufReadPost,FileReadPost   *.gz set nobin
706 > :  autocmd BufReadPost,FileReadPost   *.gz execute ":doautocmd BufReadPost " . expand("%:r")
707 > :  autocmd BufWritePost,FileWritePost *.gz !mv <afile> <afile>:r
708 > :  autocmd BufWritePost,FileWritePost *.gz !gzip <afile>:r
710 > :  autocmd FileAppendPre              *.gz !gunzip <afile>
711 > :  autocmd FileAppendPre              *.gz !mv <afile>:r <afile>
712 > :  autocmd FileAppendPost             *.gz !mv <afile> <afile>:r
713 > :  autocmd FileAppendPost             *.gz !gzip <afile>:r
714 > :augroup END
717 The "gzip" group is used to be able to delete any existing autocommands with
718 ":autocmd!", for when the file is sourced twice.
720 ("<afile>:r" is the file name without the extension, see |:_%:|)
722 The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost,
723 FileAppendPost and VimLeave events do not set or reset the changed flag of the
724 buffer.  When you decompress the buffer with the BufReadPost autocommands, you
725 can still exit with ":q".  When you use ":undo" in BufWritePost to undo the
726 changes made by BufWritePre commands, you can still do ":q" (this also makes
727 "ZZ" work).  If you do want the buffer to be marked as modified, set the
728 'modified' option.
730 To execute Normal mode commands from an autocommand, use the ":normal"
731 command.  Use with care!  If the Normal mode command is not finished, the user
732 needs to type characters (e.g., after ":normal m" you need to type a mark
733 name).
735 If you want the buffer to be unmodified after changing it, reset the
736 'modified' option.  This makes it possible to exit the buffer with ":q"
737 instead of ":q!".
739                                                         *autocmd-nested*
740 By default, autocommands do not nest.  If you use ":e" or ":w" in an
741 autocommand, Vim does not execute the BufRead and BufWrite autocommands for
742 those commands.  If you do want this, use the "nested" flag for those commands
743 in which you want nesting.  For example:
744 >       :autocmd FileChangedShell *.c nested e!
745 The nesting is limited to 10 levels to get out of recursive loops.
747 It's possible to use the ":au" command in an autocommand.  This can be a
748 self-modifying command!  This can be useful for an autocommand that should
749 execute only once.
751 There is currently no way to disable the autocommands.  If you want to write a
752 file without executing the autocommands for that type of file, write it under
753 another name and rename it with a shell command.
755 Note: When reading a file (with ":read file" or with a filter command) and the
756 last line in the file does not have an <EOL>, Vim remembers this.  At the next
757 write (with ":write file" or with a filter command), if the same line is
758 written again as the last line in a file AND 'binary' is set, Vim does not
759 supply an <EOL>.  This makes a filter command on the just read lines write the
760 same file as was read, and makes a write command on just filtered lines write
761 the same file as was read from the filter.  For example, another way to write
762 a compressed file:
764 > :autocmd FileWritePre *.gz   set bin|'[,']!gzip
765 > :autocmd FileWritePost *.gz  undo|set nobin
767                                                         *autocommand-pattern*
768 You can specify multiple patterns, separated by commas.  Here are some
769 examples:
771 > :autocmd BufRead   *          set tw=79 nocin ic infercase fo=2croq
772 > :autocmd BufRead   .letter    set tw=72 fo=2tcrq
773 > :autocmd BufEnter  .letter    set dict=/usr/lib/dict/words
774 > :autocmd BufLeave  .letter    set dict=
775 > :autocmd BufRead,BufNewFile   *.c,*.h set tw=0 cin noic
776 > :autocmd BufEnter  *.c,*.h    abbr FOR for (i = 0; i < 3; ++i)<CR>{<CR>}<Esc>O
777 > :autocmd BufLeave  *.c,*.h    unabbr FOR
779 For makefiles (makefile, Makefile, imakefile, makefile.unix, etc.):
781 > :autocmd BufEnter  ?akefile*  set include=^s\=include
782 > :autocmd BufLeave  ?akefile*  set include&
784 To always start editing C files at the first function:
786 > :autocmd BufRead   *.c,*.h    1;/^{
788 Without the "1;" above, the search would start from wherever the file was
789 entered, rather than from the start of the file.
791                                                 *skeleton* *template*
792 To read a skeleton (template) file when opening a new file:
794 > autocmd BufNewFile  *.c       0r ~/vim/skeleton.c
795 > autocmd BufNewFile  *.h       0r ~/vim/skeleton.h
796 > autocmd BufNewFile  *.java    0r ~/vim/skeleton.java
798 To insert the current date and time in a *.html file when writing it:
800 > autocmd BufWritePre,FileWritePre *.html   ks|call LastMod()|'s
801 > fun LastMod()
802 >   if line("$") > 20
803 >     let l = 20
804 >   else
805 >     let l = line("$")
806 >   endif
807 >   exe "1," . l . "g/Last modified: /s/Last modified: .*/Last modified: " .
808 >   \ strftime("%Y %b %d")
809 > endfun
811 You need to have a line "Last modified: <date time>" in the first 20 lines
812 of the file for this to work.  Vim replaces <date time> (and anything in the
813 same line after it) with the current date and time.  Explanation:
814         ks              mark current position with mark 's'
815         call LastMod()  call the LastMod() function to do the work
816         's              return the cursor to the old position
817 The LastMod() function checks if the file is shorter than 20 lines, and then
818 uses the ":g" command to find lines that contain "Last modified: ".  For those
819 lines the ":s" command is executed to replace the existing date with the
820 current one.  The ":execute" command is used to be able to use an expression
821 for the ":g" and ":s" commands.  The date is obtained with the strftime()
822 function.  You can change its argument to get another date string.
824 When entering :autocmd on the command-line, completion of events and command
825 names may be done (with <Tab>, CTRL-D, etc.) where appropriate.
827 Vim executes all matching autocommands in the order that you specify them.
828 It is recommended that your first autocommand be used for all files by using
829 "*" as the file pattern.  This means that you can define defaults you like
830 here for any settings, and if there is another matching autocommand it will
831 override these.  But if there is no other matching autocommand, then at least
832 your default settings are recovered (if entering this file from another for
833 which autocommands did match).  Note that "*" will also match files starting
834 with ".", unlike Unix shells.
836                                                     *autocmd-searchpat*
837 Autocommands do not change the current search patterns.  Vim saves the current
838 search patterns before executing autocommands then restores them after the
839 autocommands finish.  This means that autocommands do not affect the strings
840 highlighted with the 'hlsearch' option.  Within autocommands, you can still
841 use search patterns normally, e.g., with the "n" command.
842 If you want an autocommand to set the search pattern, such that it is used
843 after the autocommand finishes, use the ":let @/ =" command.
844 The search-highlighting cannot be switched off with ":nohlsearch" in an
845 autocommand.  Use the 'h' flag in the 'viminfo' option to disable search-
846 highlighting when starting Vim.
848  vim:tw=78:ts=8:sw=8: