diff --git a/home-manager/editor/neovim.nix b/home-manager/editor/neovim.nix index ccc52e22..708f39b4 100644 --- a/home-manager/editor/neovim.nix +++ b/home-manager/editor/neovim.nix @@ -739,6 +739,50 @@ in -- See `:help vim.diagnostic.*` for documentation on any of the below functions vim.keymap.set('n', 'ld', builtin.diagnostics, { desc = "LSP diagnostics" }) + -- https://gist.github.com/RaafatTurki/64d89abf326e9fce6eb717f7c1f8a97e + function LspRename() + local curr_name = vim.fn.expand("") + local value = vim.fn.input("LSP Rename: ", curr_name) + local lsp_params = vim.lsp.util.make_position_params() + + if not value or #value == 0 or curr_name == value then return end + + -- request lsp rename + lsp_params.newName = value + vim.lsp.buf_request(0, "textDocument/rename", lsp_params, function(_, res, ctx, _) + if not res then return end + + -- apply renames + local client = vim.lsp.get_client_by_id(ctx.client_id) + vim.lsp.util.apply_workspace_edit(res, client.offset_encoding) + + -- print renames + local changed_files_count = 0 + local changed_instances_count = 0 + + if (res.documentChanges) then + for _, changed_file in pairs(res.documentChanges) do + changed_files_count = changed_files_count + 1 + changed_instances_count = changed_instances_count + #changed_file.edits + end + elseif (res.changes) then + for _, changed_file in pairs(res.changes) do + changed_instances_count = changed_instances_count + #changed_file + changed_files_count = changed_files_count + 1 + end + end + + -- compose the right print message + print(string.format("renamed %s instance%s in %s file%s. %s", + changed_instances_count, + changed_instances_count == 1 and "" or "s", + changed_files_count, + changed_files_count == 1 and "" or "s", + changed_files_count > 1 and "To save them run ':wa'" or "" + )) + end) + end + -- Use LspAttach autocommand to only map the following keys -- after the language server attaches to the current buffer vim.api.nvim_create_autocmd('LspAttach', { @@ -760,7 +804,7 @@ in print(vim.inspect(vim.lsp.buf.list_workspace_folders())) end, { buffer = ev.buf, desc = "LSP list workspaces" }) vim.keymap.set('n', 'lt', builtin.lsp_type_definitions, { buffer = ev.buf, desc = "LSP type definitions" }) - vim.keymap.set('n', 'lr', vim.lsp.buf.rename, { buffer = ev.buf, desc = "LSP rename" }) + vim.keymap.set('n', 'lr', LspRename, { buffer = ev.buf, desc = "LSP rename" }) vim.keymap.set({'n', 'v'}, 'la', vim.lsp.buf.code_action, { buffer = ev.buf, desc = "LSP code action" }) vim.keymap.set('n', 'f', function() vim.lsp.buf.format { async = true }