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

How do I apply different settings for specific file types in Vim?

Answer

autocmd FileType python setlocal expandtab shiftwidth=4

Explanation

Vim's autocmd FileType lets you apply settings automatically whenever a specific file type is detected. This is the standard way to have per-language indentation, formatting, or other options without manually changing settings every time you open a file.

How it works

  • autocmd — define an automatic command that fires on an event
  • FileType python — the event: triggered when Vim sets the filetype to python
  • setlocal — apply the setting only to the current buffer (not globally)
  • expandtab shiftwidth=4 — use spaces instead of tabs, 4 spaces per indent level

Put this in your ~/.vimrc to make it permanent.

Example

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

" Go: tabs only
autocmd FileType go setlocal noexpandtab tabstop=4 shiftwidth=4

" Markdown: enable spell check and wrap
autocmd FileType markdown setlocal spell textwidth=80 wrap

" JavaScript: 2-space indentation
autocmd FileType javascript setlocal expandtab shiftwidth=2 softtabstop=2

Tips

  • Use an augroup to avoid duplicate autocmds on vimrc reload:
    augroup MyFiletypeSettings
      autocmd!
      autocmd FileType python setlocal expandtab shiftwidth=4
    augroup END
    
  • :set filetype? shows the current buffer's filetype
  • :setlocal vs :set: always use setlocal inside FileType autocmds so settings don't bleed into other buffers
  • You can also place settings in ~/.vim/ftplugin/python.vim — Vim loads these automatically

Next

How do I visually select a double-quoted string including the quotes themselves?