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

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

Answer

autocmd FileType {lang} setlocal {options}

Explanation

Vim's autocmd FileType lets you apply settings that only take effect when editing a specific file type. This means you can have 4-space indentation for Python, 2-space tabs for JavaScript, and hard tabs for Go — all automatically, without changing settings manually every time you switch files.

How it works

  • autocmd FileType triggers when Vim detects the file type of a buffer
  • {lang} is the filetype name (e.g., python, javascript, go, html, ruby)
  • setlocal applies the settings only to the current buffer, not globally
  • You can set multiple options in one command, separated by spaces

Add these to your vimrc and they apply automatically every time you open a matching file.

Example

" Python: 4 spaces, no tabs
autocmd FileType python setlocal tabstop=4 shiftwidth=4 expandtab

" JavaScript/TypeScript: 2 spaces
autocmd FileType javascript,typescript setlocal tabstop=2 shiftwidth=2 expandtab

" Go: hard tabs, 4-wide
autocmd FileType go setlocal tabstop=4 shiftwidth=4 noexpandtab

" Markdown: wrap text, spell check
autocmd FileType markdown setlocal wrap linebreak spell

" Makefiles: must use hard tabs
autocmd FileType make setlocal noexpandtab

When you open main.py, Vim detects filetype=python and applies 4-space indentation. Open app.js next, and Vim switches to 2-space indentation for that buffer. Each buffer keeps its own settings.

Tips

  • Wrap your autocmds in an augroup to prevent duplicates when re-sourcing your vimrc:
augroup FiletypeSettings
  autocmd!
  autocmd FileType python setlocal ts=4 sw=4 et
  autocmd FileType javascript setlocal ts=2 sw=2 et
augroup END
  • The autocmd! inside the group clears previous entries, preventing them from stacking up
  • Use :set filetype? to check what filetype Vim detected for the current buffer
  • You can set more than just indentation — textwidth, colorcolumn, foldmethod, commentstring, and any local option works
  • For more complex per-filetype configuration, create files in ~/.vim/after/ftplugin/ — e.g., ~/.vim/after/ftplugin/python.vim is automatically sourced for Python files
  • Make sure filetype plugin indent on is in your vimrc to enable filetype detection
  • Use comma-separated filetypes to apply the same settings to multiple languages: autocmd FileType html,xml,svg setlocal ts=2 sw=2 et

Next

How do I edit multiple lines at once using multiple cursors in Vim?