Search code examples
vim

Vim: set filetype based on file content


How do I set the filetype of a a file in Vim based on the contents of the file, not the extension?

Vim seems to have that ability to read the shebang and infer the file type even if the file has no extension. How do I define arbitrary flags to look for in the file and change the file type. Eg, eg if the file starts with /** @flow */ set the filetype to javascript.flow.


Solution

  • See here and here for more information, but here are some options:

    " Search entire file
    au BufRead * if search('mypattern', 'nw') | setlocal ft=myfiletype | endif
    
    " Search first line only
    au BufRead * if getline(1) =~ 'mypattern' | setlocal ft=myfiletype | endif