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?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.Sign up to join this community
The best method is to put those settings in
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.
You can do this with autocommands in your
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
augroups 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
Used autocmd and FileType
autocmd FileType html setlocal shiftwidth=4 tabstop=4