*autocmd.txt*   For Vim version 5.0u.  Last modification: 1997 Dec 28


		  VIM REFERENCE MANUAL    by Bram Moolenaar


Automatic commands					*autocommand*

1. Introduction			|autocmd-intro|
2. Defining autocommands	|autocmd-define|
3. Removing autocommands	|autocmd-remove|
4. Listing autocommands		|autocmd-list|
5. Events			|autocmd-events|
6. Patterns			|autocmd-patterns|
7. Groups			|autocmd-groups|
8. Executing autocommands	|autocmd-execute|
9. Using autocommands		|autocmd-use|

{Vi does not have any of these commands}

==============================================================================
1. Introduction						*autocmd-intro*

You can specify commands to be executed automatically for when reading or
writing a file, when entering or leaving a buffer or window, and when exiting
Vim.  For example, you can create an autocommand to set the 'cindent' option
for files matching *.c.  Autocommands can also be used to implement advanced
features, such as editing compressed files (see |gzip-example|).  These
commands are normally put in your .vimrc or .exrc file.

WARNING: Using autocommands is very powerful, and may lead to unexpected side
effects.  Be careful not to destroy your text.
- It's a good idea to first do some testing on an expendable copy of a file
  first.  For example: If you use autocommands to decompress a file when
  starting to edit it, make sure that the autocommands for compressing when
  writing work correctly.
- Be prepared for an error halfway through (e.g., disk full).  Vim will mostly
  be able to undo the changes to the buffer, but you may have to clean up the
  changes to other files by hand (e.g., compress a file that has been
  decompressed).
- If the BufRead* events allow you to edit a compressed file, the FileRead*
  events should do the same (to be able to do recovery in some rare cases).
  It's a good idea to use the same autocommands for the File* and Buf* events
  when possible.

The autocommand feature is only included if Vim has been compiled with AUTOCMD
defined.  If the output of ":version" contains "+autocmd" it is included (this
is the default), if it contains "-autocmd" then the autocommand feature
doesn't work.

==============================================================================
2. Defining autocommands				*autocmd-define*

Note: The ":autocmd" command cannot be followed by another command, since any
'|' is considered part of the command.

							*:au* *:autocmd*
:au[tocmd] [group] {event} {pat} [nested] {cmd}
			Add {cmd} to the list of commands that will be
			automatically executed on {event} for a file matching
			{pat}.  The {cmd} is always added after existing
			autocommands, so that the autocommands are executed in
			the order in which they were given.  See
			|autocmd-nest| for [nested].

Note that special characters (e.g., "%", "<cword>") in the ":autocmd"
arguments are not expanded when the autocommand is defined.  These will be
expanded when the Event is recognized, and the {cmd} is executed.  The only
exception is that "<sfile>" is expanded when the autocmd is defined.  Example:

>	:au BufEnter *.html so <sfile>:h/html.vim

Here <sfile> is expanded to the file that contains this line.

When your .vimrc file is sourced twice, the autocommands will appear twice.
To avoid this, put this command in your .vimrc file, before defining
autocommands:

>	:autocmd!	" Remove ALL auto-commands.

If you don't want to remove all autocommands, you could use a variable, to
make sure the autocommands are only included once:

>	:if !exists("autocommands_loaded")
>	:  let autocommands_loaded = 1
>	:  au ...
>	:endif

When the [group] argument is not given, the current group, as defined with
":augroup", is used.  Otherwise the group defined with [group] is used.  Note
that [group] must have defined before.  You cannot define a new group with
":au group ...".  Use ":augroup" for that.

While testing autocommands, it might be useful to set the 'verbose' option:
>	:set verbose=9
This makes the executed autocommands to be echoed.

==============================================================================
3. Removing autocommands				*autocmd-remove*

:au[tocmd]! [group] {event} {pat} [nested] {cmd}
			Remove all auto-commands associated with {event} and
			{pat}, and add the command {cmd}.  See |autocmd-nest|
			for [nested].

:au[tocmd]! [group] {event} {pat}
			Remove all auto-commands associated with {event} and
			{pat}.

:au[tocmd]! [group] * {pat}
			Remove all auto-commands associated with {pat} for all
			events.

:au[tocmd]! [group] {event}
			Remove ALL auto-commands for {event}.

:au[tocmd]! [group]	Remove ALL auto-commands.

When the [group] argument is not given, the current group, as defined with
":augroup", is used.  Otherwise the group defined with [group] is used.

==============================================================================
4. Listing autocommands					*autocmd-list*

:au[tocmd] [group] {event} {pat}
			Show the auto-commands associated with {event} and
			{pat}.

:au[tocmd] [group] * {pat}
			Show the auto-commands associated with {pat} for all
			events.

:au[tocmd] [group] {event}
			Show all auto-commands for {event}.

:au[tocmd] [group]	Show all auto-commands.

If the [group] argument is given, only the auto-commands for [group] are
listed.  When the [group] argument is not given, the auto-commands for ALL
groups are listed.  Note that this is different from defining and removing
autocommands.

==============================================================================
5. Events						*autocmd-events*

					*autocommand-events* *{event}*
These events are recognized.  Case is ignored, for example "BUFread" and
"bufread" can be used instead of "BufRead".

							*BufNewFile*
BufNewFile			When starting to edit a file that doesn't
				exist.  Can be used to read in a skeleton
				file.
							*BufReadPre*
BufReadPre			When starting to edit a new buffer, before
				reading the file into the buffer.  Not used
				when the file doesn't exist.
						*BufRead* *BufReadPost*
BufRead or BufReadPost		When starting to edit a new buffer, after
				reading the file into the buffer, before
				executing the modelines.  This does NOT work
				for ":r file".  Not used when the file doesn't
				exist.  Also used after succesfully recovering
				a file.
							*FileReadPre*
FileReadPre			Before reading a file with a ":read" command.
							*FileReadPost*
FileReadPost			After reading a file with a ":read" command.
				Note that the '[ and '] marks are set to the
				first and last line of the read, this can be
				used to operate on the just read lines.
							*FilterReadPre*
FilterReadPre			Before reading a file from a filter command.
				The file name of the current buffer is used to
				match with the pattern, not the name of the
				temporary file that is the output of the
				filter command.
							*FilterReadPost*
FilterReadPost			After reading a file from a filter command.
				Like FilterReadPre, the file name of the
				current buffer is used.
							*StdinReadPre*
StdinReadPre			Before reading from stdin into the buffer.
				Only used when the "-" argument was used when
				Vim was started |--|.
							*StdinReadPost*
StdinReadPost			After reading from the stdin into the buffer,
				before executing the modelines.  Only used
				when the "-" argument was used when Vim was
				started |--|.
						*BufWrite* *BufWritePre*
BufWrite or BufWritePre		Before writing the whole buffer to a file.
							*BufWritePost*
BufWritePost			After writing the whole buffer to a file
				(should undo the commands for BufWritePre).
							*FileWritePre*
FileWritePre			Before writing to a file, when not writing the
				whole buffer.
							*FileWritePost*
FileWritePost			After writing to a file, when not writing the
				whole buffer.
							*FileAppendPre*
FileAppendPre			Before appending to a file.
							*FileAppendPost*
FileAppendPost			After appending to a file.
							*FilterWritePre*
FilterWritePre			Before writing a file for a filter command.
				The file name of the current buffer is used to
				match with the pattern, not the name of the
				temporary file that is the input for the
				filter command.
							*FilterWritePost*
FilterWritePost			After writing a file for a filter command.
				Like FilterWritePre, the file name of the
				current buffer is used.
							*FileChangedShell*
FileChangedShell		After a shell command is run, and vim notices
				that the modification time of the current file
				has changed since editing started.  Run in
				place of the 'has been changed' message.  See
				|timestamp|.  Useful for reloading related
				buffers which are affected by a single
				command.
							*BufEnter*
BufEnter			After entering a buffer.  Useful for setting
				options for a file type.  Also executed when
				starting to edit a buffer, after the
				BufReadPost autocommands.
							*BufLeave*
BufLeave			Before leaving to another buffer.  Also when
				leaving or closing the current window and the
				new current window is not for the same buffer.
BufUnload						*BufUnload*
				Before unloading a buffer.  This is when the
				text in the buffer is going to be freed.  This
				may be after a BufWritePost and before a
				BufDelete.
BufDelete						*BufDelete*
				Before deleting a buffer from the buffer list.
				The BufUnload may be called first (if the
				buffer was loaded).
							*WinEnter*
WinEnter			After entering another window.  Not done for
				the first window, when Vim is just started.
				Useful for setting the window height.
				If the window is for another buffer, the
				BufEnter autocommands are executed after the
				WinEnter autocommands.
							*TermChanged*
TermChanged			After the value of 'term' was changed.  Useful
				for re-loading the syntax file to update the
				colors, fonts and other terminal-dependent
				settings.  Executed for all loaded buffers.
							*WinLeave*
WinLeave			Before leaving to another window.  If the
				window to be entered is for a different
				buffer, the BufLeave autocommands are executed
				before the WinLeave autocommands.
							*VimLeave*
VimLeave			Before exiting Vim, just before writing the
				.viminfo file.  There is no VimEnter event,
				because you can use the .vimrc for that.

For READING FILES there are three possible pairs of events, only one pair is
used at a time:
BufNewFile			starting to edit a non-existant file
BufReadPre	BufReadPost	starting to edit an existing file
FilterReadPre	FilterReadPost	read the temp file with filter output
FileReadPre	FileReadPost	any other file read

Note that the autocommands for the *ReadPre events and all the Filter events
are not allowed to change the current buffer.  You will get an error message
if this happens anyway.  This is to prevent the file to be read into the wrong
buffer.

The 'eventignore' option can be used to ignore a number of events, or all
events.

==============================================================================
6. Patterns						*autocmd-patterns*

The file pattern is tested for a match against the file name in one of two
ways:
1. When there is no '/' in the pattern, it is tested for a match against just
   the tail part of the file name (without its leading directory path).
2. When there is a '/' in the pattern, it will be tested against the short
   file name (as you typed it) and the full file name (after expanding it to a
   full path, resolving symbolic links).

Examples:
>	:autocmd BufRead /vim/src/*.c	set wrap
>	:autocmd BufRead /tmp/*.c	set ts=5
The first matches for all files that have a path that ends in "/vim/src/*.c".
If you have a link from "/tmp/test.c" to "/home/nobody/vim/src/test.c", and
you start editing "/tmp/test.c", the example autocommand will both match.

Note:  When the pattern starts with "/", this does not mean it matches the
root directory.  It can match any '/' in the file name.  To match the root
directory, use "^/".

Note that for all systems the '/' character is used for path separator, also
on MS-DOS and OS/2.  This was done because the backslash is difficult to use
in a pattern, and to make the autocommands portable accross different systems.

Note that using ~ in a file name (for home directory) doesn't work.  Use a
pattern that matches the full path name, for example "*home/user/.cshrc".

==============================================================================
7. Groups						*autocmd-groups*

Autocommands can be put together in a group.  This is useful to be able to
remove or execute a group of autocommands.  For example, all the autocommands
for syntax highlighting are put in the "highlight" group, to be able to
execute ":doautoall highlight BufRead" when the GUI starts.

When no specific group is selected, the default group is used.  It does not
have a name.  You cannot execute the autocommands from the default group
separately, only by executing autocommands for all groups.

Normally, when executing autocommands automatically, the autocommands for all
groups are used.  The group only matters when executing autocommands with
":doautocmd" or ":doautoall", or when defining or deleting autocommands.

The group name can contain any characters, except white space.  The group name
"end" is reserved (also in uppercase).

							*:aug* *:augroup*
:aug[roup] {name}		Define the autocmd group name for the
				following ":autocmd" commands.  When using the
				name "end" or "END", the default group is
				selected.

To enter autocommands for a specific group, this is the normal method:
1. Select the group with ":augroup {name}".
2. Delete any old autocommands with ":au!".
3. Define the autocommands.
4. Go back to the default group with "augroup END".

Example:
>	:augroup uncompress
>	:  au!
>	:  au BufEnter *.gz	%!gunzip
>	:augroup END

This avoids the risc of having the autocommands defined twice, when the .vimrc
file is sourced again.

==============================================================================
8. Executing autocommands				*autocmd-execute*

Autocommands can also be executed non-automatically.  This can be used after
adjusting the autocommands, or when the wrong autocommands have been executed
(file pattern match was wrong).

Note that the 'eventignore' option applies here too.  Events listed in this
option will not cause any commands to be executed.

							*:do* *:doautocmd*
:do[autocmd] [group] {event} [fname]
			Apply the autocommands matching [fname] (default:
			current file name) for {event} to the current buffer.
			This can be used when the current file name does not
			match the right pattern, after changing settings, or
			to execute autocommands for a certain event.
			It's possible to use this inside an autocommand too,
			so you can base the autocommands for one extension on
			another extension.  Example:
>				:au Bufenter *.cpp so ~/.vimrc_cpp
>				:au Bufenter *.cpp doau BufEnter x.c
			Be careful for endless loops.  See |autocmd-nest|.

			When the [group] argument is not given, the
			autocommands for all gropus are executed.  When the
			[group] argument is included, only the matching
			autocommands for that group are executed.  Note: when
			an undefined group name is used, you will get an error
			message for an illegal event name.

						*:doautoa* *:doautoall*
:doautoa[ll] [group] {event} [fname]
			Like ":doautocmd", but execute it for each loaded
			buffer.  Careful: Don't use this for autocommands that
			delete a buffer, change to another buffer or change
			the contents of a buffer, the result will be
			unpredictable.  It is only meant to perform
			autocommands that set options, change highlighting,
			and things like that.

==============================================================================
9. Using autocommands					*autocmd-use*

Before the *ReadPre event the '[ mark is set to the line just above where the
new lines will be inserted.
Before the *ReadPost event the '[ mark is set to the first line that was just
read, the '] mark to the last line.
Careful: '[ and '] will change when using commands that change the buffer.

"<afile>" can be used for the file name that is being read, in commands where
a file name is expected (where you can also use "%" for the current file
name) |:<afile>|.

Examples for reading compressed files:
> :autocmd! BufReadPre,FileReadPre   *.gz set bin
> :autocmd  BufReadPost,FileReadPost *.gz '[,']!gunzip
> :autocmd  BufReadPost,FileReadPost *.gz set nobin
> :autocmd  BufReadPost,FileReadPost *.gz execute ":doautocmd BufReadPost " . %:r

NOTE: When using the examples given, any existing autocommands for the same
event/pattern combination will be removed, because of the '!'.

For WRITING FILES there are four possible pairs of events, only one pair is
used at a time:
BufWritePre	BufWritePost	writing the whole buffer
FilterWritePre	FilterWritePost	writing to the temp file with filter input
FileAppendPre	FileAppendPost	appending to a file
FileWritePre	FileWritePost	any other file write

Note that the *WritePost commands should undo any changes to the buffer that
were caused by the *WritePre commands, otherwise writing the file will have
the side effect of changing the buffer.

Before executing the autocommands, the buffer from where the lines are to be
written is temporarily made the current buffer.  Unless the autocommands
change the current buffer, or delete the previously current buffer, the
previously current buffer is made the current buffer again.

The *WritePre and *AppendPre autocommands must not delete the buffer from
where the lines are to be written.

Before executing the *WritePre and *AppendPre autocommands the '[ mark is set
to the first line that will be written, the '] mark to the last line.
Careful: '[ and '] will change when using commands that change the buffer.

"<afile>" can be used for the file name that is being written, in commands
where a file name is expected (where you can also use "%" for the current file
name) |:<afile>|.

							*gzip-example*
Examples for writing compressed files:
> :autocmd! BufWritePost,FileWritePost	*.gz !mv <afile> <afile>:r
> :autocmd  BufWritePost,FileWritePost	*.gz !gzip <afile>:r
>
> :autocmd! FileAppendPre		*.gz !gunzip <afile>
> :autocmd  FileAppendPre		*.gz !mv <afile>:r <afile>
> :autocmd! FileAppendPost		*.gz !mv <afile> <afile>:r
> :autocmd  FileAppendPost		*.gz !gzip <afile>:r

("<afile>:r" is the file name without the extension, see |:_%:|)

The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost,
FileAppendPost and VimLeave events do not set or reset the changed flag of the
buffer.  When you decompress the buffer with the BufReadPost autocommands, you
can still exit with ":q".  When you use ":undo" in BufWritePost to undo the
changes made by BufWritePre commands, you can still do ":q" (this also makes
"ZZ" work).  If you do want the buffer to be marked as modified, set the
'modified' option.

To execute Normal mode commands from an autocommand, use the ":normal"
command.  Use with care!  If the Normal mode command is not finished, the user
needs to type characters (e.g., after ":normal m" you need to type a mark
name).

If you want the buffer not to be modified after changing it, reset the
'modified' option.  This makes it possible to exit the buffer with ":q"
instead of ":q!".

							*autocmd-nest*
By default, autocommands do not nest.  If you use ":e" or ":w" in an
autocommand, the BufRead and BufWrite autocommands are not executed for those
commands.  If you do want this, the "nested" flag must be given for those
commands where nesting is desired.  For example:
>	:autocmd FileChangedShell *.c nested e!
The nesting is limited to 10 levels, to get out of recursive loops.

It's possible to use the ":au" command in an autocommand. This can be a
self-modifying command!  This can be useful for an autocommand that should
only be executed once.

There is currently no way to disable the autocommands.  If you want to write a
file without executing the autocommands for that type of file, write it under
another name and rename it with a shell command.

Note: When reading a file (with ":read file" or with a filter command) and the
last line in the file does not have an end-of-line character, this is
remembered.  At the next write (with ":write file" or with a filter command),
if the same line is written again as the last line in a file AND 'binary' is
set, no end-of-line character is written.  This makes a filter command on the
just read lines write the same file as was read, and makes a write command on
just filtered lines write the same file as was read from the filter.  For
example, another way to write a compressed file:

> :autocmd FileWritePre *.gz   set bin|'[,']!gzip
> :autocmd FileWritePost *.gz  undo|set nobin

							*autocommand-pattern*
Multiple patterns may be given separated by commas.  Here are some examples:

> :autocmd BufRead   *		set tw=79 nocin ic infercase fo=2croq
> :autocmd BufRead   .letter	set tw=72 fo=2tcrq
> :autocmd BufEnter  .letter	set dict=/usr/lib/dict/words
> :autocmd BufLeave  .letter	set dict=
> :autocmd BufRead,BufNewFile   *.c,*.h	set tw=0 cin noic
> :autocmd BufEnter  *.c,*.h	abbr FOR for(i = 0; i < 3; i++)^M{^M}^[O
> :autocmd BufLeave  *.c,*.h	unabbr FOR

For makefiles (makefile, Makefile, imakefile, makefile.unix, etc.):

> :autocmd BufEnter  ?akefile*	set include=^s\=include
> :autocmd BufLeave  ?akefile*	set include&

To always start editing C files at the first function:

> :autocmd BufRead   *.c,*.h	1;/^{

Without the "1;" above, the search would start from wherever the file was
entered, rather than from the start of the file.

To read a skeleton file for new C files:

> :autocmd BufNewFile  *.c	0r ~/.skeleton.c
> :autocmd BufNewFile  *.h	0r ~/.skeleton.h

To insert the current date and time in a *.html file when writing it:

> :autocmd BufWritePre,FileWritePre *.html ks|1,20g/Last modification: /normal f:lD:read !date^MkJ's

(to insert the ^M type CTRL-V CTRL-M)
You need to have a line "Last modification: <date time>" in the first 20 lines
of the file for this to work.  The <date time> (and anything in the same line
after it) will be replaced with the current date and time.  Explanation:
	ks		mark current position with mark 's'
	1,20g/pattern/	find lines that contain the pattern
	normal f:	find the ':'
	lD		delete the old date and time
	!date^M		read the current date and time into the next line
	kJ		Join the date and time with the previous line
	's		return the cursor to the old position

When entering :autocmd on the command line, completion of events and command
names may be done (with <Tab>, CTRL-D, etc.) where appropriate.

All matching auto-commands will be executed in the order that they were
specified.  It is recommended that your first auto-command be used for all
files by using "*" as the file pattern.  This means that you can define
defaults you like here for any settings, and if there is another matching
auto-command it will override these.  But if there is no other matching
auto-command, then at least your default settings are recovered (if entering
this file from another for which auto-commands did match).  Note that "*" will
also match files starting with ".", unlike Unix shells.

The search patterns are saved and restored, such that the autocommands do not
change them.  While executing autocommands, you can use search patterns
normally, e.g. with the "n" command.  After the autocommands finish, the
patterns from before the autocommand execution are restored.  This means that
the strings highlighted with the 'hlsearch' option are not affected by
autocommands.

 vim:tw=78:ts=8:sw=8:
