Skip to content

Commit

Permalink
fix: move cursor correctly with multi-line text edits
Browse files Browse the repository at this point in the history
Closes #1123
  • Loading branch information
Saghen committed Feb 1, 2025
1 parent 7483cd9 commit ac2ecd6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lua/blink/cmp/completion/accept/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,10 @@ local function accept(ctx, item, callback)
else
table.insert(all_text_edits, item.textEdit)
text_edits_lib.apply(all_text_edits)
-- TODO: should move the cursor only by the offset since text edit handles everything else?
ctx.set_cursor({ ctx.get_cursor()[1], item.textEdit.range.start.character + #item.textEdit.newText + offset })

local new_cursor = text_edits_lib.get_apply_end_position(item.textEdit)
new_cursor[2] = new_cursor[2] + offset
ctx.set_cursor(new_cursor)
end

-- Let the source execute the item itself
Expand Down
24 changes: 24 additions & 0 deletions lua/blink/cmp/lib/text_edits.lua
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,28 @@ function text_edits.clamp_range_to_bounds(range)
return range
end

--- The TextEdit.range.start/end indicate the range of text that will be replaced.
--- This means that the end position will be the range *before* applying the edit.
--- This function gets the end position of the range *after* applying the edit.
--- This may be used for placing the cursor after applying the edit.
---
--- TODO: handle multiple text edits since they can edit the text that comes
--- before the current edit
---
--- @param text_edit lsp.TextEdit
--- @return number[] (1, 0) indexed line and column
function text_edits.get_apply_end_position(text_edit)
local lines = vim.split(text_edit.newText, '\n')
local last_line_len = #lines[#lines]
local line_count = #lines

local end_line = text_edit.range['end'].line + line_count - 1

local end_col = last_line_len
if line_count == 1 then end_col = end_col + text_edit.range['end'].character end

-- Convert from 0-indexed to (1, 0)-indexed to match nvim cursor api
return { end_line + 1, end_col }
end

return text_edits

0 comments on commit ac2ecd6

Please sign in to comment.