user16117431
user16117431

Reputation:

Set different settings for different languages in Vim

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

Upvotes: 1

Views: 4029

Answers (2)

user16117431
user16117431

Reputation:

autocmd FileType python call Python_settings()

function! Python_settings()
  setlocal tabstop=4
  setlocal shiftwidth=4
  setlocal expandtab
endfunction

Upvotes: 5

romainl
romainl

Reputation: 196506

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.

Upvotes: 4

Related Questions