Skip to content

Commit

Permalink
home-manager/neovim: better LSP rename
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagokokada committed Nov 15, 2024
1 parent 74b16d0 commit 3165000
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion home-manager/editor/neovim.nix
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,50 @@ in
-- See `:help vim.diagnostic.*` for documentation on any of the below functions
vim.keymap.set('n', '<space>ld', builtin.diagnostics, { desc = "LSP diagnostics" })
-- https://gist.github.com/RaafatTurki/64d89abf326e9fce6eb717f7c1f8a97e
function LspRename()
local curr_name = vim.fn.expand("<cword>")
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', {
Expand All @@ -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', '<Leader>lt', builtin.lsp_type_definitions, { buffer = ev.buf, desc = "LSP type definitions" })
vim.keymap.set('n', '<Leader>lr', vim.lsp.buf.rename, { buffer = ev.buf, desc = "LSP rename" })
vim.keymap.set('n', '<Leader>lr', LspRename, { buffer = ev.buf, desc = "LSP rename" })
vim.keymap.set({'n', 'v'}, '<Leader>la', vim.lsp.buf.code_action, { buffer = ev.buf, desc = "LSP code action" })
vim.keymap.set('n', '<Leader>f', function()
vim.lsp.buf.format { async = true }
Expand Down

0 comments on commit 3165000

Please sign in to comment.