nvim set filetype picker

whenever i open a new buffer and paste stuff into it, formatting is lost. this happens because neovim doesn’t know what type of file it’s dealing with. setting the correct filetype manually each time is tedious. that’s where a filetype picker comes in handy.

changing filetypes in neovim can be faster. this post introduces a lua-based telescope picker for setting filetypes in neovim.

the problem

switching between different file types in neovim requires typing commands like :set filetype=python. this takes time, especially when working with multiple file types.

the solution

we’ve made a telescope-based filetype picker that lets you select from a list of common filetypes. here’s the core code:

local M = {}
local pickers = require "telescope.pickers"
local finders = require "telescope.finders"
local conf = require("telescope.config").values
local actions = require "telescope.actions"
local action_state = require "telescope.actions.state"
local filetypes = {
{ "Python", "python" },
{ "JavaScript", "javascript" },
-- ... more filetypes ...
}
function M.telescope_filetype_picker()
pickers.new({}, {
prompt_title = "Select filetype",
finder = finders.new_table {
results = filetypes,
entry_maker = function(entry)
return {
value = entry,
display = entry[1],
ordinal = entry[1],
}
end,
},
sorter = conf.generic_sorter(),
attach_mappings = function(prompt_bufnr, map)
actions.select_default:replace(function()
actions.close(prompt_bufnr)
local selection = action_state.get_selected_entry()
if selection then
vim.cmd("set filetype=" .. selection.value[2])
end
end)
return true
end,
}):find()
end
return M

how to use

  1. save the code in your neovim config (e.g., ~/.config/nvim/lua/my_utils/filetype_picker.lua)
  2. add this to your init.lua:
local filetype_picker = require('my_utils.filetype_picker')
vim.keymap.set('n', '<leader>ft', filetype_picker.telescope_filetype_picker, { desc = 'Pick filetype' })
  1. press <leader>ft in normal mode to open the picker
  2. select your filetype

customization

to add or remove filetypes, edit the filetypes table in the code. this lets you adapt it to your needs and commonly used languages.

conclusion

this telescope-based filetype picker makes changing filetypes in neovim faster. it reduces the time spent on editor commands, letting you focus more on coding. try it and see if it helps your neovim workflow.