1

Is there a way to get filetype for given extension or filename

For example:

let my_f='text.rb'
let my_ft=GetFileType(my_f)
echo my_ft
" should output ruby
  • 1
    easiest would be to load the file for editing and check the filetype option. Next best option, would be to parse the filetype.vim file (e.g. the filetypedetect autocommand group) – Christian Brabandt Oct 19 '16 at 6:19
3

As Christian said, parsing the expression won't be the easier way. I'd even say that's insufficient. Some filetypes share the same file extension. In that case, vim parses a few lines from the files to deduce exactly their filetype.

Otherwise, you could indeed parse filetype.vim, but instead, I'd parse the result of execute('autocmd filetypedetect') with filter(). If for your extension you get a setf {filetype} then you have a direct hit. Otherwise, it means vim does some magic with lines of the file to disambiguate the information.

let ext = expand('%:e') 
let matching = uniq(sort(filter(split(execute('autocmd filetypedetect'), "\n"), 'v:val =~ "\*\.".ext')))

if len(matching) == 1 && matching[0]  =~ 'setf'
   return matchstr(matching[0], 'setf\s\+\zs\k\+')
endif
throw "sorry, I can't know"

PS: execute() requires vim7.4-2008. With earlier versions we have to play with :redir. See lh#askvim#exe()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.