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

How do I add custom filetype detection for a new file extension without modifying Vim's built-in filetypes?

Answer

ftdetect/{filetype}.vim

Explanation

Vim automatically sources every file in ftdetect/ directories on the runtimepath when filetype detection runs. Creating ~/.vim/ftdetect/mytype.vim (or ~/.config/nvim/ftdetect/mytype.vim) lets you add custom filetype associations for new extensions, patterns, or tools — without ever touching Vim's built-in filetype files.

How it works

  • Vim's :filetype detect sources all ftdetect/*.vim files from every directory in runtimepath
  • Each file in ftdetect/ should only set the filetype (via setfiletype or set filetype=)
  • setfiletype is preferred: it respects any filetype already set by a prior rule and won't override it
  • Files in ftdetect/ fire after Vim's built-in detection, so they can override defaults

Example

Detect .tf files as Terraform and .jsonc as JSON with comments:

" ~/.vim/ftdetect/terraform.vim
autocmd BufRead,BufNewFile *.tf,*.tfvars setfiletype terraform
" ~/.vim/ftdetect/jsonc.vim
autocmd BufRead,BufNewFile *.jsonc,tsconfig*.json setfiletype jsonc

Now when you open a .tf file, Vim automatically sets filetype=terraform.

Tips

  • For complete filetype support, also create ~/.vim/syntax/mytype.vim for syntax highlighting and ~/.vim/ftplugin/mytype.vim for buffer-local settings (indent, commentstring, etc.)
  • Filetype names must be alphanumeric with dots (e.g., c.doxygen for C+doxygen)
  • Check what Vim detected with :set filetype? or :echo &filetype
  • List all filetype detection files with :scriptnames after opening a file of that type

Next

How do I control how many lines Ctrl-U and Ctrl-D scroll?