summaryrefslogtreecommitdiff
path: root/nvim/lua/config/file-rename.lua
blob: 0d56e731482f20e20fe376eb3d7219d26f5b2523 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
-- Saves the files changed by a workspace edit. Only those, not all buffers like :wall would
local function save_edited_files(edit)
	local uris = vim.tbl_keys(edit.changes or {})
	for _, change in ipairs(edit.documentChanges or {}) do
		table.insert(uris, change.textDocument and change.textDocument.uri or change.uri)
	end
	for _, uri in ipairs(uris) do
		local buf = vim.uri_to_bufnr(uri)
		if vim.api.nvim_buf_is_loaded(buf) and vim.bo[buf].modified then
			vim.api.nvim_buf_call(buf, function()
				vim.cmd("silent update")
			end)
		end
	end
end

-- Updates references (imports, etc.) when a file or folder is renamed/moved in mini.files
local function update_references(from, to)
	local params = { files = { { oldUri = vim.uri_from_fname(from), newUri = vim.uri_from_fname(to) } } }
	for _, client in ipairs(vim.lsp.get_clients()) do
		if client:supports_method("workspace/willRenameFiles") then
			local response = client:request_sync("workspace/willRenameFiles", params, 3000, 0)
			if response and response.result then
				vim.lsp.util.apply_workspace_edit(response.result, client.offset_encoding)
				save_edited_files(response.result)
			end
		end
		if client:supports_method("workspace/didRenameFiles") then
			client:notify("workspace/didRenameFiles", params)
		end
	end
end

vim.api.nvim_create_autocmd("User", {
	pattern = { "MiniFilesActionRename", "MiniFilesActionMove" },
	callback = function(event)
		update_references(event.data.from, event.data.to)
	end,
})