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

How do I set options that only apply to certain file types?

Answer

autocmd FileType python setlocal ...

Explanation

Using autocmd FileType with setlocal, you can configure settings that only apply when editing files of a specific type.

How it works

  • autocmd FileType python setlocal tabstop=4 applies only to Python files
  • setlocal makes the setting buffer-local
  • The autocommand fires when the file type is detected

Example

autocmd FileType python setlocal tabstop=4 shiftwidth=4 expandtab
autocmd FileType go setlocal tabstop=4 noexpandtab
autocmd FileType javascript setlocal shiftwidth=2
autocmd FileType html setlocal shiftwidth=2

Tips

  • Wrap in augroup to prevent duplicates
  • Alternatively, use ftplugin files: ~/.vim/ftplugin/python.vim
  • :setlocal only affects the current buffer
  • :filetype plugin indent on enables the built-in filetype system
  • Check filetype with :set filetype?

Next

How do you yank a single word into a named register?