How do I get the correct filetype based on a file extension?

For example, I have a function that accepts a string and sets the filetype for a given buffer. I want the function to be able to handle, for example, both ‘js’ and ‘javascript’, and set the file type correctly to ‘javascript’.

Setting the filetype for the buffer is easy enough, but how can I translate a file extension to a filetype? Asides from defining mappings myself for every filetype I might use.

Check out neovim/filetype.lua at master · neovim/neovim · GitHub

See :h vim.filetype.match():

local filetype = vim.filetype.match { filename = fname }

This will set the buffer based on a given filename, which is not quite what I’m looking for. I basically want to pass in a string of a file extension or valid filetype (e.g. ‘md’, ‘js’, ‘javascript’, ‘lua’ etc.) and output a string of the matching filetype (e.g. ‘markdown’, ‘javascript’, ‘lua’ etc.).

In filetype.lua this is done with a lookup table but it is private so I’d have to copy that lookup table and expose it to my plugin, which is what I was hoping to avoid.

Are you sure you aren’t mistaken? I don’t have acces to the docs, but reading the source of match very much looks like it does what you want (with a disclaimer about ambiguity).

(PSA: Always make sure to mention your Neovim version, because things can change quite a bit.)

On current master (which will be 0.8 soon), vim.filetype.match definitely does not set the filetype, it only returns it as a string. Your use case is explicitly supported and was one of the main motivations in making this change.

1 Like

Ah, ok that makes sense. I’m on stable.