0

I normally use 4 spaces for indentation. However I occasionally submit patches to OSS projects and some of them use tabs. When I do that I'll usually just edit my ~/.vimrc and change set expandtab to set noexpandtab. Of course then I'll forget to unset it, which is only a very minor annoyance.

I've also recently been toying with setting the VIMINIT variable if I open a shell to work on that project. I would just need to re-set it if I close that shell. Not the worst thing in the world but ...

I'm wondering if there is a way to tell vim to use certain settings like noexpandtab based on if I'm under a certain directory tree or not. That way I just set it once in a config file and not have to think about it again on this workstation.

Don Seiler
  • 460
  • 5
  • 16

1 Answers1

4

It's very simple to achieve this with :autocmd. This line, for example, would set noexpandtab for everything under the /projects directory:

autocmd BufRead /projects/* setlocal noexpandtab

Just add that with the appropriate adjustments to your .vimrc. To learn more, please check the help pages on :autocmd and autocmd-patterns.

sidyll
  • 57,726
  • 14
  • 108
  • 151
  • That worked great, thanks! – Don Seiler Jun 28 '18 at 21:42
  • 1
    Not `setlocal`? I often see `au BufRead ... set ...` pattern, would that not set expandtab also in other, innocent buffers when this is triggered? – Amadan Jun 29 '18 at 09:16
  • @Amadan there are the two kind of options, local and global. setlocal is used to set global options locally. Since this particular one already is local (please confirm this in the docs), setlocal is not necessary. – sidyll Jun 29 '18 at 11:14
  • 1
    @sidyll I thought it’s vice-versa. `:help local-options` says “for each buffer-local option there also is a global value ... With `:set` both the local and global values are changed”; while `:help :setlocal` says “Not all options have a local value. If the option doesn’t have a local value the global value is set. ”. – Amadan Jun 29 '18 at 11:24
  • @Amadan you are correct, I'm sorry. It's impressive how I have misunderstood this for so many years. `:set` on a buffer-local won't affect other existing buffers, but it does set the global default which is used for new buffers from that point forward. Thank you very much for noticing this, and teaching me. Regarding your second help citation, I think it is a different case that probably refers to settings such as `encoding` which are not applicable buffer or window only. Thus `:setlocal` will act as `:set` anyway. – sidyll Jun 29 '18 at 12:45
  • 2
    @DonSeiler I've updated the answer to use `:setlocal` which is the appropriated command in this case. Please update your command as well, if you used `:set`. I'm sorry, my apologies for making this mistake. – sidyll Jun 29 '18 at 12:48
  • OK thanks. I'll be sure to do that. – Don Seiler Jun 29 '18 at 12:49