Skip to content

Commit 7e7bbea

Browse files
authored
feat: add extract variable command (#5)
1 parent 8aed200 commit 7e7bbea

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
local ui = require('java.utils.ui')
2+
3+
local M = {
4+
---@class java-refactor.RenameAction
5+
---@field length number
6+
---@field offset number
7+
---@field uri string
8+
9+
---Rename a given item
10+
---@param arguments java-refactor.RenameAction[]
11+
['java.action.rename'] = function(arguments)
12+
for _, rename in ipairs(arguments) do
13+
local buffer = vim.uri_to_bufnr(rename.uri)
14+
local line
15+
16+
vim.api.nvim_buf_call(buffer, function()
17+
line = vim.fn.byte2line(rename.offset)
18+
end)
19+
20+
local start_char = rename.offset - vim.fn.line2byte(line) + 1
21+
local end_char = start_char + rename.length
22+
23+
local name = ui.input('Variable Name')
24+
25+
if not name then
26+
return
27+
end
28+
29+
vim.api.nvim_buf_set_text(
30+
buffer,
31+
line - 1,
32+
start_char,
33+
line - 1,
34+
end_char,
35+
{ name }
36+
)
37+
end
38+
end,
39+
}
40+
41+
return M
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
local class = require('java-core.utils.class')
2+
local notify = require('java-core.utils.notify')
3+
local lsp_refactor_commands = require('java-refactor.lsp-refactor-commands')
4+
5+
local JdtlsClient = require('java-core.ls.clients.jdtls-client')
6+
7+
---@class java-refactor.ClientCommands
8+
---@field client lsp.Client
9+
local RefactorCommands = class()
10+
11+
function RefactorCommands:_init(client)
12+
self.client = client
13+
self.jdtls_client = JdtlsClient(client)
14+
end
15+
16+
function RefactorCommands:extract_variable()
17+
local context = vim.lsp.util.make_range_params(0)
18+
context.context = {}
19+
context.context.diagnostics = vim.lsp.diagnostic.get_line_diagnostics(0)
20+
21+
local buffer = vim.api.nvim_get_current_buf()
22+
23+
local selection =
24+
self.jdtls_client:java_infer_selection('extractVariable', context, buffer)
25+
26+
local edit = self.jdtls_client:java_get_refactor_edit(
27+
'extractVariable',
28+
context,
29+
{},
30+
selection,
31+
buffer
32+
)
33+
34+
vim.lsp.util.apply_workspace_edit(edit.edit, 'utf-8')
35+
36+
RefactorCommands.run_lsp_client_command(
37+
edit.command.command,
38+
edit.command.arguments
39+
)
40+
end
41+
42+
function RefactorCommands.run_lsp_client_command(command_name, arguments)
43+
local command
44+
45+
if lsp_refactor_commands[command_name] then
46+
command = lsp_refactor_commands[command_name]
47+
else
48+
command = vim.lsp.commands[command_name]
49+
end
50+
51+
if not command then
52+
notify.error('Command "' .. command_name .. '" is not supported')
53+
return
54+
end
55+
56+
command(arguments)
57+
end
58+
59+
return RefactorCommands

0 commit comments

Comments
 (0)