I'd like to have different indentations based on the type of file I am working on. For example, working on a .c
file I'd like my indentation be 4 spaces. In .html
files I'd like to (have to) work with tabs.
How do I achieve that?
The best method is to put those settings in ~/.vim/after/ftplugin/<filetype>.vim
.
For HTML (assuming you want 4 characters-wide tabs):
~/.vim/after/ftplugin/html.vim
setlocal shiftwidth=4
setlocal softtabstop=4
setlocal noexpandtab
Using an ftplugin is prefered to using autocommands because Vim already does filetype checks by itself and already tries to source the adequate ftplugin so there's no reason to force even more checks and reimplement the wheel.
-- edit --
Assuming you have filetype plugin on
in your vimrc
— which you should — Vim will try to detect the filetype of the files you edit and, once the correct filetype is found and set for the buffer, try to source the corresponding ftplugin in these standard locations:
$VIMRUNTIME/ftplugin/html.vim
~/.vim/ftplugin/html.vim
~/.vim/ftplugin/after/html.vim
All of that happens automatically so, if your filetype is recognized by Vim, there is absolutely no reason to add any filetype detection logic: just add your settings to the right ftplugin and you are good.
filetype plugin indent on
in your vimrc
.
filetype plugin on
is set, vim's path includes the ftplugin/<filetype>.vim
and after/ftplugin/<filetype>/vim
files in its path.
Commented
Feb 3, 2015 at 20:24
softtabstop
and shiftwidth
will use a mix of tabs and spaces. You're usually better off using tabstop
.
You can do this with autocommands in your .vimrc
.
For example, I have a function html_like_mode
that sets up various things for editing HTML files. In my .vimrc
, I have:
au BufNewFile,BufRead *.html call s:html_like_mode()
That keys off of the file extension. You can also key off of the filetype, if you have that enabled:
au FileType perl setlocal equalprg=perltidy
As you can see, you can have it do any command there. So you could easily do a setlocal shiftwidth 4
for your *.c files.
augroup
allows you to group related autocommands into named groups. (See here to learn about Autocommand Groups.) We use augroup
s to add autocommands to ~/.vimrc
in a way that won't add a duplicate every time we source it.
augroup vimrc
autocmd!
augroup END
autocmd vimrc FileType html setlocal shiftwidth=4 tabstop=4
autocmd FileType plaintex,tex,context setlocal indentexpr=
.