Skip to content

Commit

Permalink
refactor: extract_cursor_position
Browse files Browse the repository at this point in the history
  • Loading branch information
mrcjkb committed Oct 1, 2024
1 parent 56959fa commit 6a0247d
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions lua/rustaceanvim/commands/move_item.lua
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,28 @@ local function get_params(up)
return params
end

---@param prev_text_edit rustaceanvim.lsp.TextEdit
---@param text_edit rustaceanvim.lsp.TextEdit
local function text_edit_line_range_diff(prev_text_edit, text_edit)
return math.max(0, text_edit.range.start.line - prev_text_edit.range['end'].line - 1)
- (prev_text_edit.range.start.line == text_edit.range.start.line and 1 or 0)
end

---@param text_edits rustaceanvim.lsp.TextEdit[]
local function extract_cursor_position(text_edits)
local cursor = { text_edits[1].range.start.line }
local prev_text_edit
for _, text_edit in ipairs(text_edits) do
if text_edit.newText and text_edit.insertTextFormat == 2 then
if not cursor[2] then
if prev_text_edit then
cursor[1] = cursor[1]
+ math.max(0, text_edit.range.start.line - prev_text_edit.range['end'].line - 1)
- (prev_text_edit.range.start.line == text_edit.range.start.line and 1 or 0)
end
local pos_start = string.find(text_edit.newText, '%$0')
local lines = vim.split(string.sub(text_edit.newText, 1, pos_start), '\n')
local total_lines = #lines
cursor[1] = cursor[1] + total_lines
if pos_start then
cursor[2] = (total_lines == 1 and text_edit.range.start.character or 0) + #lines[total_lines] - 1
end
if text_edit.newText and text_edit.insertTextFormat == 2 and not cursor[2] then
cursor[1] = cursor[1] + (prev_text_edit and text_edit_line_range_diff(prev_text_edit, text_edit) or 0)
local snippet_pos_start = string.find(text_edit.newText, '%$0')
local lines = vim.split(string.sub(text_edit.newText, 1, snippet_pos_start), '\n')
local line_count = #lines
cursor[1] = cursor[1] + line_count
if snippet_pos_start then
local start_offset = line_count == 1 and text_edit.range.start.character or 0
local last_line_length = #lines[line_count] - 1
cursor[2] = start_offset + last_line_length
end
end
prev_text_edit = text_edit
Expand Down

0 comments on commit 6a0247d

Please sign in to comment.