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

How do I change the filetype of the current buffer to get correct syntax highlighting and indent rules?

Answer

:setfiletype {filetype}

Explanation

:setfiletype {filetype} sets the filetype option for the current buffer only if it has not already been set. To unconditionally change it, use :set filetype={filetype} or the shorthand :setf {filetype}. This triggers all filetype-specific autocmds, syntax rules, and indent plugins for the new type — the full filetype detection machinery, not just syntax highlighting.

How it works

  • :set filetype=python — forces the buffer to be treated as Python, regardless of file extension
  • :setfiletype python — same but only if filetype has not been set yet (safe to use in autocommands without overriding manual settings)
  • Setting filetype triggers FileType autocmds, loads ftplugin/{type}.vim, and activates syntax/{type}.vim

Example

Open a file with an unusual extension and set it as a bash script:

:set filetype=sh

Switch a .conf file to nginx syntax:

:set filetype=nginx

Check the current filetype:

:set filetype?

Tips

  • This is different from :set syntax=nginx — setting syntax only changes highlighting but does not trigger filetype plugins or indent files
  • Use :setfiletype in ~/.vim/ftdetect/ scripts to add custom filetype detection rules without overriding existing ones
  • After changing filetype, run :filetype detect if you want Vim to re-run all detection rules from scratch
  • Common use case: JSON files often need :set filetype=jsonc to get comment support in editors that respect it

Next

How do I create a Vim mapping where the keys it produces are computed dynamically at runtime?