Skip to content

Commit a07bb0d

Browse files
authored
feat(lsp): preserve cursor position for move_item command (#532)
1 parent 1e97a9e commit a07bb0d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

lua/rustaceanvim/commands/move_item.lua

+27
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,41 @@ local function get_params(up)
1212
return params
1313
end
1414

15+
local function extract_cursor_position(text_edits)
16+
local cursor = { text_edits[1].range.start.line }
17+
local prev_te
18+
for _, te in ipairs(text_edits) do
19+
if te.newText and te.insertTextFormat == 2 then
20+
if not cursor[2] then
21+
if prev_te then
22+
cursor[1] = cursor[1]
23+
+ math.max(0, te.range.start.line - prev_te.range['end'].line - 1)
24+
- (prev_te.range.start.line == te.range.start.line and 1 or 0)
25+
end
26+
local pos_start = string.find(te.newText, '%$0')
27+
local lines = vim.split(string.sub(te.newText, 1, pos_start), '\n')
28+
local total_lines = #lines
29+
cursor[1] = cursor[1] + total_lines
30+
if pos_start then
31+
cursor[2] = (total_lines == 1 and te.range.start.character or 0) + #lines[total_lines] - 1
32+
end
33+
end
34+
end
35+
prev_te = te
36+
end
37+
return cursor
38+
end
39+
1540
-- move it baby
1641
local function handler(_, result, ctx)
1742
if result == nil or #result == 0 then
1843
return
1944
end
45+
local cursor = extract_cursor_position(result)
2046
local overrides = require('rustaceanvim.overrides')
2147
overrides.snippet_text_edits_to_text_edits(result)
2248
vim.lsp.util.apply_text_edits(result, ctx.bufnr, vim.lsp.get_client_by_id(ctx.client_id).offset_encoding)
49+
vim.api.nvim_win_set_cursor(0, cursor)
2350
end
2451

2552
local rl = require('rustaceanvim.rust_analyzer')

0 commit comments

Comments
 (0)