1

I want to set different settings for different languages or filetypes.

Every language has own style guides (e.g., different tab size, spaces instead tabs, etc.) so I can't add settings below in my .vimrc since I use vim with several languages. The settings should be separate for each language

Python files settings for 4 spaces indent style:

set tabstop=4 
set shiftwidth=4

JavaScript files settings for 2 spaces indent style:

set tabstop=2 
set shiftwidth=2
0

2 Answers 2

6
autocmd FileType python call Python_settings()

function! Python_settings()
  setlocal tabstop=4
  setlocal shiftwidth=4
  setlocal expandtab
endfunction
Sign up to request clarification or add additional context in comments.

Comments

4

Vim comes with built-in filetype detection that, among other things, makes it possible to do things differently for different filetypes.

For that mechanism to work, you need either of the following lines in your vimrc:

filetype on
filetype indent on
filetype plugin on
filetype indent plugin on    " the order of 'indent' and 'plugin' is irrelevant
  • The first line only enables filetype detection.
  • The second line is like the first, plus filetype-specific indenting.
  • The third line is like the first, plus filetype-specific settings.
  • The fourth line enables everything.

Assuming you have either of the following lines:

filetype plugin on
filetype indent plugin on

you can create $HOME/vim/after/ftplugin/javascript.vim with the following content:

setlocal tabstop=2
setlocal shiftwidth=2
  • :setlocal is used instead of :set to make those settings buffer-local and thus prevent them to leak into other buffers.
  • the after directory is used to make sure your settings are sourced last.

Still assuming you have ftplugins enabled, there is nothing to do for Python as the default ftplugin already sets those options the way you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.