Making a custom Neovim filetype picker with mini.pick
It took me a minute to find a good example, so I’ll post this in case it helps anyone else.
For you Vimmers out there, here’s an example of how to make your own custom picker using Neovim and mini.pick, part of the very popular mini.nvim plugin. In this case, I’m adding a picker to set the active buffer’s filetype.
local function pick_filetype()
-- Grab the current buffer before firing the picker
-- so we can update it later when we're inside
-- the picker's buffer.
local current_buf = vim.api.nvim_get_current_buf()
-- Get the choices for the picker. In this case,
-- all available filetypes.
local filetypes = vim.fn.getcompletion('', 'filetype')
-- Launch the picker with our custom choices and
-- handler.
require('mini.pick').start({
source = {
name = 'Filetypes',
items = filetypes,
choose = function(item)
-- Handle the user's choice.
vim.bo[current_buf].filetype = item
-- (Optional) Pop a notification to help us
-- know it's working.
vim.notify("Set filetype to " .. item)
end,
},
})
end
-- Add a keymap to run it
vim.keymap.set('n', '<leader>bt', pick_filetype, { desc = 'Pick filetype' })
I created this file with my code: ~/.config/nvim/lua/custom/filetype_picker.lua.
And then I wrapped the code in a module.
Unnecessary but possibly more idiomatic, and leaves room to add configuration parameters later.
(If this is bad form, please email and educate me!)
local M = {}
function M.setup()
-- (insert all the code from the block above)
end
return M
And then from init.lua or the like, invoke it like so:
require("custom.filetype_picker").setup()
Not too shabby. Cheers to echasnovski and all the other contributors for making such a great library!