vimtricks.wiki Concise Vim tricks, one at a time.

How do I set different Vim options for specific programming languages?

Answer

autocmd FileType python setlocal ts=4 sw=4 et

Explanation

Using autocmd FileType, you can configure Vim to automatically apply buffer-local settings whenever a file of a particular type is opened. This is the standard way to have different indentation, formatting, or keybinding preferences per language without affecting other file types.

How it works

  • autocmd FileType {filetype} triggers whenever Vim detects a buffer's filetype (via filename extension, modeline, or content detection)
  • setlocal applies the setting only to the current buffer, not globally — this is critical for per-filetype config
  • You can chain multiple settings and even define buffer-local mappings
  • Place these in your ~/.vimrc or in ~/.vim/after/ftplugin/{filetype}.vim for cleaner organization

Example

Add these to your vimrc for language-specific indentation:

" Python: 4-space indentation
autocmd FileType python setlocal tabstop=4 shiftwidth=4 expandtab

" Go: tabs, not spaces
autocmd FileType go setlocal tabstop=4 shiftwidth=4 noexpandtab

" HTML/CSS: 2-space indentation
autocmd FileType html,css setlocal tabstop=2 shiftwidth=2 expandtab

" Markdown: enable spell check and line wrapping
autocmd FileType markdown setlocal spell wrap linebreak

Tips

  • Wrap autocmds in an augroup to prevent duplicates on vimrc reload: augroup filetypes | autocmd! | autocmd FileType ... | augroup END
  • Use setlocal instead of set to avoid bleeding settings into other buffers
  • For buffer-local mappings, add <buffer>: autocmd FileType python nnoremap <buffer> <leader>r :!python3 %<CR>
  • The alternative ftplugin approach puts settings in ~/.vim/after/ftplugin/python.vim — one file per filetype, no autocmd needed

Next

How do I ignore whitespace changes when using Vim's diff mode?