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 iffiletypehas not been set yet (safe to use in autocommands without overriding manual settings)- Setting
filetypetriggersFileTypeautocmds, loadsftplugin/{type}.vim, and activatessyntax/{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— settingsyntaxonly changes highlighting but does not trigger filetype plugins or indent files - Use
:setfiletypein~/.vim/ftdetect/scripts to add custom filetype detection rules without overriding existing ones - After changing filetype, run
:filetype detectif you want Vim to re-run all detection rules from scratch - Common use case: JSON files often need
:set filetype=jsoncto get comment support in editors that respect it