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