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)setlocalapplies 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
~/.vimrcor in~/.vim/after/ftplugin/{filetype}.vimfor 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
augroupto prevent duplicates on vimrc reload:augroup filetypes | autocmd! | autocmd FileType ... | augroup END - Use
setlocalinstead ofsetto avoid bleeding settings into other buffers - For buffer-local mappings, add
<buffer>:autocmd FileType python nnoremap <buffer> <leader>r :!python3 %<CR> - The alternative
ftpluginapproach puts settings in~/.vim/after/ftplugin/python.vim— one file per filetype, no autocmd needed