Skip to content

Commit 85d704b

Browse files
committed
feat(lsp): preserve cursor position for move_item command
1 parent 1e97a9e commit 85d704b

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

lua/rustaceanvim/commands/move_item.lua

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,43 @@ 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+
-- $0 -> Nothing
35+
te.newText = string.gsub(te.newText, '%$%d', '')
36+
-- ${0:_} -> _
37+
te.newText = string.gsub(te.newText, '%${%d:(.-)}', '%1')
38+
end
39+
prev_te = te
40+
end
41+
return cursor
42+
end
43+
1544
-- move it baby
1645
local function handler(_, result, ctx)
1746
if result == nil or #result == 0 then
1847
return
1948
end
20-
local overrides = require('rustaceanvim.overrides')
21-
overrides.snippet_text_edits_to_text_edits(result)
49+
local cursor = extract_cursor_position(result)
2250
vim.lsp.util.apply_text_edits(result, ctx.bufnr, vim.lsp.get_client_by_id(ctx.client_id).offset_encoding)
51+
vim.api.nvim_win_set_cursor(0, cursor)
2352
end
2453

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

0 commit comments

Comments
 (0)