I am now a Python/Ruby polyglot and have a need to switch out values in my .vimrc depending on the filetype I'm using.
I need tabstop=2
, softtabstop=2
for Ruby and tabstop=4
, softtabstop=4
for Python. My Google-fu has failed as to how to do this. Any ideas on how to detect file extension?
Make sure you have this in your ~/.vimrc
:
filetype plugin on
Then create these two files in ~/.vim/ftplugin
:
In ~/.vim/ftplugin/python.vim
:
setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab
In ~/.vim/ftplugin/ruby.vim
:
setlocal tabstop=2 softtabstop=2 shiftwidth=2 expandtab
(I added shiftwidth
and expandtab
because you almost definitely want those as well.)
Vim will detect the file type and then run the appropriate file based on the type. This is nice because it keeps clutter out of your ~/.vimrc
. You can do this for any filetype that Vim recognizes. When you're editing a file, you can use :set filetype?
to see what kind of file Vim thinks it is.
First, the dirty way:
autocmd FileType ruby setlocal tabstop=2 softtabstop=2
autocmd FileType python setlocal expandtab tabstop=4 softtabstop=4
You need setlocal
to keep those settings from being applied in other buffers.
Then, the less dirty way:
augroup filetypes
autocmd!
autocmd FileType ruby setlocal tabstop=2 softtabstop=2
autocmd FileType python setlocal expandtab tabstop=4 softtabstop=4
augroup END
A named augroup
is good for organizing your ~/.vimrc
but it can also be enabled/disabled in one go in case of need.
When you reload your ~/.vimrc
, which can happen a lot if you tinker a lot, autocmd
s never replace previous ones: they are added and added and added and it can lead to serious issues. autocmd!
removes all the autocmd
s in the current augroup
before adding them back to avoid problems.
Then, the clean way:
Add the following lines to ~/.vim/after/ftplugin/ruby.vim
:
setlocal tabstop=2
setlocal softtabstop=2
Add the following lines to ~/.vim/after/ftplugin/python.vim
:
setlocal expandtab
setlocal tabstop=4
setlocal softtabstop=4
Even when you organize them cleanly and do autocmd!
to keep them from piling up, autocmd
s bound to the FileType
event still pose a problem: they replicate Vim's built-in filetype detection mechanism. Assuming you have filetype plugin indent on
in your ~/.vimrc
, that mechanism already reacts to the FileType
of your buffer and tries to source scripts contained in ~/.vim/ftplugin/
and ~/.vim/after/ftplugin/
.
That's the most appropriate place for filetype-specific settings.
You need to base it off the file type like this:
au FileType ruby set tabstop=2 softtabstop=2
au FileType python set expandtab tabstop=4 softtabstop=4
That would go in your .vimrc or any file that gets loaded after it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With