10

For example, what's the difference between calling this command this way:

autocmd BufWritePre * call StripTrailingWhitespace()

vs. this way (with the bang after autocmd):

autocmd! BufWritePre * call StripTrailingWhitespace()

1 Answer 1

10

The command

autocmd! BufWritePre * call StripTrailingWhitespace()

Removes all autocmds for the event BufWritePre and the file pattern * from the default autocmd-group and sets a new autocmd for this event and pattern to call StripTrailingWhitespace().

Example:

autocmd BufWritePre * echomsg "First"
autocmd BufWritePre * echomsg "Second"

If you then enter :autocmd BufWritePre you will get the following (plus maybe other autocmds defined for this event):

--- Autocommands ---
BufWrite
    *         echomsg "First"
              echomsg "Second"

Then you execute

autocmd! BufWritePre * echomsg "Third"

followed by :autocmd BufWritePre and you get:

--- Autocommands ---
BufWrite
    *         echomsg "Third"

So the autocmds echoing "First" and "Second" were removed and the new autocmd echoing "Third" was defined.

See :help autocmd-remove.

3
  • So does that mean there's not need to wrap my autocmd(s) in an augroup if I'm using the autocmd! {cmd} version since the previous autocmds will be cleared from the default/global group anyway?
    – aonemd
    May 5, 2019 at 12:49
  • 1
    I think I got an answer to my question. As long as you don't have a shared event between more than one autocmd! command, you're fine without augroups. Otherwise, shared event autocmd!s will clear each other. So, wrapping your autocmd commands inside an augroup is the safer option here.
    – aonemd
    May 5, 2019 at 13:31
  • 1
    @aonemd Exactly! E.g. I have one autocmd related to syntax in my vimrc and wrapped even this single cmd in a group called my_syntax_autocmds.
    – Ralf
    May 5, 2019 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.