I have done some googling and I'm surprised that I haven't found this. COuld someone explain to me simply the easiest way to change the indentation behavior of vim based on the file type? For instance if I open a python file it would indent with 2 spaces, but if I open powershell it would use 4 spaces.
Put autocmd commands based on the file suffix in your ~/.vimrc
autocmd BufRead,BufNewFile *.c,*.h,*.java set noic cin noexpandtab
autocmd BufRead,BufNewFile *.pl syntax on
The commands you're looking for are probably ts= and sw=
I usually work with expandtab
set, but that's bad for makefiles. I recently added:
:autocmd FileType make set noexpandtab
to the end of my .vimrc file and it recognizes Makefile, makefile, and *.mk as makefiles and does not expand tabs. Presumably, you can extend this.
Use ftplugins or autocommands to set options. (:h ftplugin for more information)
In ~/.vim/ftplugin/python.vim:
setlocal sw=2 sts=2 et
And don't forget to turn them on in ~/.vimrc
filetype plugin indent on
Or in ~/.vimrc
au FileType python setl sw=2 sts=2 et
I would also suggest learning the difference between 'ts' and 'sts'. A lot of people don't know about 'sts'.
You can add .vim
files to be executed whenever vim switches to a particular filetype.
For example, I have a file ~/.vim/after/ftplugin/html.vim
with this contents:
setlocal shiftwidth=2
setlocal tabstop=2
Which causes vim to use tabs with a width of 2 characters for indenting (the noexpandtab
option is set globally elsewhere in my configuration).
This is described here: http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4, scroll down to the section on filetype plugins.
While you can configure Vim's indentation just fine using the indent plugin or manually using the settings, I recommend using a python script called Vindect that automatically sets the relevant settings for you when you open a python file. Use this tip to make using Vindect even more effective. When I first started editing python files created by others with various indentation styles (tab vs space and number of spaces), it was incredibly frustrating. But Vindect along with this indent file
Also recommend: