2

I'm trying to figure out what is the proper way to prevent autocmds from being redundantly repeated.

Here are articles which I have already read:

Well, so we have our .vimrc and we need to use autocmds inside it. We could use it like this (1):

autocmd BufWritePre * :call Function()

...or like this (2):

autocmd! BufWritePre * :call Function()

...or like this (3):

augroup OurGroup
  autocmd!
  autocmd BufWritePre * :call Function()
augroup END

...or like this (4):

augroup OurGroup
  autocmd!
augroup END

autocmd OurGoup BufWritePre * :call Function()

Questions:

  • Is it correct that we should never use the 1st version?

  • Is it correct that we should always use the 2nd or 3rd or 4th version?

  • Which version is better: 2nd or 4th? (I don't mention the 3rd version because it is quite similar to the 4th one).

  • 3
    I always use the 3rd variant in my scripts. It's a habit I learned long ago. Guess from a vim mailing list. Useful in files, that might be sourced multiple times (like vimrc during testing). – Ralf Feb 3 at 17:26
  • 1
    The 3rd is actually the one I'd recommend, since everything is grouped together, you only refer to the group name once and it starts by completely clearing the group, then defining autocommands. It's also easy to move from (1) to (3) since all you have to do is surround the autocmds in a new augroup block and you're done. – filbranden Feb 3 at 17:28
  • @Ralf You say about testing, but is it useful in regular workflow? Also, I already hear about this "sourced-multiple-times-case", but I haven't found any explanation at which circumstances it occurs. – john c. j. Feb 3 at 18:37
  • @filbranden But isn't (4) better? For example, if you have 3 autocmds in .vimrc, it will take 12 lines with (3), and only 6 lines with (4). Probably it have some pitfalls? – john c. j. Feb 3 at 18:46
  • 1
    @johnc.j. You asked about regular workflow". I can't tell you. It just "feels" right and sometimes it is good to do the right thing, even if it is not needed. For me the "sourced-multiple-times-case" happen as I answer questions on stackexchange :-). – Ralf Feb 3 at 21:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.