if-statementvimautocommand

Vim: Use "if" in augroup?


I just want to define an autocommand that executes some external commands. For example, delete some auto-generated files after compilation. I work on both Windows and Linux, and the external commands used are different on these two platforms.

Therefore, I can define:

    if has("win32")
        autocmd foo bar_win
    else
        autocmd foo bar_nix
    endif

If I want to define this autocommand within a augroup, should I simply put this piece of code into an augroup like:

    augroup fooo
        autocmd!
        if has("win32")
            autocmd foo bar_win
        else
            autocmd foo bar_nix
        endif
    augroup END

I tried this method, and it seems this works. I am wondering if this is the correct way to do it. Another way I can think about is to write the external commands into a function within which I can use if statement. Then define autocommand in the usual way and call this function. Which is better?

Thanks!


Solution

  • augroup foo and augroup END don't delimit a code block so it doesn't matter if you put your feature check there or elsewhere.

    But you could follow this alternative pattern if you want safety and flexibility.

    1. Define an empty autocommand group somewhere near the top of your vimrc:

      augroup foo
          autocmd!
      augroup END
      
    2. Run your feature check later:

      if has("win32")
          autocmd foo Event * command for windows
      else
          autocmd foo Event * command for unices
      endif
      

      Since your autocommands belong to group foo they are correctly removed when you :source $MYVIMRC.