feat(nvim): allow disabling cmp sources

Add a new command "CmpToggle" and functions to turn off/on a cmp source.
nixos
Moritz Böhme 2023-10-26 09:47:21 +02:00
parent 58c8efa332
commit 2c2824a395
2 changed files with 97 additions and 0 deletions

View File

@ -74,6 +74,9 @@ with builtins;
}
{
plugin = nvim-cmp;
keys = [
{ key = "<leader>tc"; cmd = "<cmd>CmpToggle<cr>"; desc = "Toggle Cmp sources"; }
];
conf = readFile ./lua/nvim-cmp.lua;
event = [ "InsertEnter" ];
dependencies = [

View File

@ -120,3 +120,97 @@ cmp.event:on(
},
})
)
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 all_sources = vim.deepcopy(cmp.get_config().sources)
local find = function(sources, name)
for k, source in ipairs(sources) do
if source.name == name then
return k
end
end
return nil
end
local is_active = function(name)
local active_sources = cmp.get_config().sources
local index = find(active_sources, name)
return index ~= nil
end
local enable_source = function(name, force)
if force or not is_active(name) then
local source_index = find(all_sources, name)
if source_index ~= nil then
local active_sources = cmp.get_config().sources
local source = all_sources[source_index]
table.insert(active_sources, 1, source)
cmp.setup({ sources = active_sources })
end
end
end
local disable_source = function(identifier)
if type(identifier) == "string" then
identifier = find(all_sources, identifier)
end
local active_sources = cmp.get_config().sources
table.remove(active_sources, identifier)
end
local toggle_sources = function(name)
local active_sources = cmp.get_config().sources
local index = find(active_sources, name)
if index ~= nil then
disable_source(index)
else
enable_source(name, true)
end
end
-- our picker function: sources
local sources_picker = function(opts)
opts = opts or {}
pickers
.new(opts, {
prompt_title = "sources",
finder = finders.new_table({
results = vim.tbl_map(function(source)
return source.name
end, all_sources),
entry_maker = function(entry)
return {
value = entry,
display = function(tbl)
local name = tbl["ordinal"]
local active = is_active(name)
return string.format("%s %s", name, active and "" or "")
end,
ordinal = entry,
}
end,
}),
sorter = conf.generic_sorter(opts),
attach_mappings = function(prompt_bufnr, _)
actions.select_default:replace(function()
actions.close(prompt_bufnr)
local selection = action_state.get_selected_entry()
toggle_sources(selection["value"])
end)
return true
end,
})
:find()
end
-- autocommand for sources_picker
vim.api.nvim_create_user_command("CmpToggle", sources_picker, {})
-- disable sources by default
disable_source("codeium")