Skip to content

Commit f4b8340

Browse files
committed
feat(move_item): preserve cursor position
PR: simrat39#386
1 parent 71d2cf6 commit f4b8340

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

lua/rust-tools/move_item.lua

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,53 @@ local function get_params(up)
1010
return params
1111
end
1212

13+
local function extract_cursor_position(text_edits)
14+
local cursor = { text_edits[1].range.start.line }
15+
16+
local prev_te
17+
for _, te in ipairs(text_edits) do
18+
if te.newText and te.insertTextFormat == 2 then
19+
if not cursor[2] then
20+
if prev_te then
21+
cursor[1] = cursor[1]
22+
+ math.max(0, te.range.start.line - prev_te.range["end"].line - 1)
23+
- (prev_te.range.start.line == te.range.start.line and 1 or 0)
24+
end
25+
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+
30+
cursor[1] = cursor[1] + total_lines
31+
if pos_start then
32+
cursor[2] = (total_lines == 1 and te.range.start.character or 0)
33+
+ #lines[total_lines]
34+
- 1
35+
end
36+
end
37+
38+
-- $0 -> Nothing
39+
te.newText = string.gsub(te.newText, "%$%d", "")
40+
-- ${0:_} -> _
41+
te.newText = string.gsub(te.newText, "%${%d:(.-)}", "%1")
42+
end
43+
prev_te = te
44+
end
45+
return cursor
46+
end
47+
1348
-- move it baby
1449
local function handler(_, result, ctx)
15-
if result == nil then
50+
if result == nil or #result == 0 then
1651
return
1752
end
18-
rt.utils.snippet_text_edits_to_text_edits(result)
53+
local cursor = extract_cursor_position(result)
1954
vim.lsp.util.apply_text_edits(
2055
result,
2156
ctx.bufnr,
2257
vim.lsp.get_client_by_id(ctx.client_id).offset_encoding
2358
)
59+
vim.api.nvim_win_set_cursor(0, cursor)
2460
end
2561

2662
-- Sends the request to rust-analyzer to move the item and handle the response

0 commit comments

Comments
 (0)