0

Please forgive me if this has already been answered, but I am wanting to do the following within vim

set tabstop=2 expandtab

However, I only want this to apply to .c and .h files (since I also use makefiles and they need the hard tab ).

My old computer broke that I had this already in the vimrc, and any help would be appreciated

Edit: Changing Vim indentation behavior by file type seems to have answered a similar question, but I cannot find a way to make this work for the .h files unless I am being dumb

  • 1
    Typically this is placed in your personal after directory (e.g. look at `:help after`). See this post, https://vi.stackexchange.com/questions/12731/when-to-use-the-after-directory). – Patrick Bacon Mar 20 '20 at 23:15
  • Does this answer your question? [Changing Vim indentation behavior by file type](https://stackoverflow.com/questions/158968/changing-vim-indentation-behavior-by-file-type) – filbranden Mar 21 '20 at 00:39

1 Answers1

-1

I just didn't scroll down enough on this question: Changing Vim indentation behavior by file type

The one that worked for me was

autocmd BufRead,BufNewFile   *.c,*.h set ts=2 expandtab

Through the pointers in I got in the comments, I modified my solution to have the autocmd in a group and then to clear out the autocmd before running anything. leaving it as this:

:augroup cAndHeaderFiles
:       autocmd!
:       autocmd BufRead,BufNewFile   *.c,*.h set sts=2 sw=2 expandtab cindent
:augroup END
  • 3
    The solution using a `~/.vim/after/ftplugin/c.vim` file (if you're on Linux/Unix/Mac) or `$HOME/vimfiles/after/plugin/c.vim` (on Windows) is better. Also, make sure you use `setlocal`, since you only want to affect that buffer and not change the global setting. You'll also want to set `shiftwidth=2`. And it's better to set `softtabstop=2` rather than mess with `tabstop`, ideally you'd want to leave that one at 8... – filbranden Mar 21 '20 at 00:38
  • 2
    Consider reading this article that explains why auto commands should be grouped https://learnvimscriptthehardway.stevelosh.com/chapters/14.html – SergioAraujo Mar 21 '20 at 13:03
  • 1
    @filbranden Thank you for the pointer, I added the shiftwidth to the line and changes ts to sts, I now remember my friend telling me to change softtabwidth now! (A much more experienced vim user) – Johnathan R Mar 21 '20 at 23:17
  • 1
    @SergioAraujo Thank you for the link, I didn't think about potential over usage and while that wouldn't affect me here too much, I could see how as I expand my usage it will definitely have an impact – Johnathan R Mar 21 '20 at 23:18