Skip to content

Fix inserting to the end of a range #714

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions lua/conform/runner.lua
Original file line number Diff line number Diff line change
Expand Up @@ -227,23 +227,24 @@ M.apply_format = function(
local is_delete = new_line_count == 0
local is_replace = not is_insert and not is_delete
local orig_line_end = orig_line_start + orig_line_count
local new_line_end = new_line_start + new_line_count

if is_insert then
-- When the diff is an insert, it actually means to insert after the mentioned line
orig_line_start = orig_line_start + 1
orig_line_end = orig_line_end + 1
end

local replacement = util.tbl_slice(new_lines, new_line_start, new_line_end - 1)

-- For replacement edits, convert the end line to be inclusive
if is_replace then
orig_line_end = orig_line_end - 1
end
local new_line_end = new_line_start + new_line_count

local replacement = util.tbl_slice(new_lines, new_line_start, new_line_end - 1)

local should_apply_diff = not only_apply_range
or not range
or indices_in_range(range, orig_line_start, orig_line_end)

-- When the diff is an insert, it actually means to insert after the mentioned line
if is_insert then
orig_line_start = orig_line_start + 1
orig_line_end = orig_line_end + 1
end

if should_apply_diff then
local text_edit = create_text_edit(
original_lines,
Expand Down
12 changes: 12 additions & 0 deletions tests/runner_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,18 @@ print("a")
)
assert.are.same({ "a", "d", "c" }, vim.api.nvim_buf_get_lines(0, 0, -1, false))
end)

it("applies edits that are inserting at the end of the range", function()
run_formatter(
"a\nb\nc",
"a\nb\nc\nd",
{ range = {
start = { 2, 0 },
["end"] = { 3, 0 },
} }
)
assert.are.same({ "a", "b", "c", "d" }, vim.api.nvim_buf_get_lines(0, 0, -1, false))
end)
end)

it("can run the format command in the shell", function()
Expand Down