Skip to content
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

fix(subs): Avoid modifying a match that has already been altered. #147

Merged
Merged
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
16 changes: 12 additions & 4 deletions lua/textcase/shared/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,17 @@ function utils.get_current_word_info()
end

function utils.get_list(str, mode)
-- Assuming forward lookup, if Foo is modified to BarFoo, the cursor will remain in Bar,
-- using searchpos, the next occurrence of Foo will be the second part of BarFoo which was
-- already modified, entering an infinite loop, that will result into: BarBarBarBar...BarFoo
--
-- for that reason, search should be executed backwards to avoid including an edited match.

-- TODO: Optimize replacement to run only in a selected region, currently it is running in the whole buffer
local search_options = "b"
local limit = 0
local initial = nil
local next = vim.fn.searchpos(str)
local next = vim.fn.searchpos(str, search_options)

local region = utils.get_visual_region(nil, true, mode)

Expand All @@ -283,7 +291,7 @@ function utils.get_list(str, mode)
initial = { next[1], next[2] }
end
end
next = vim.fn.searchpos(str)
next = vim.fn.searchpos(str, search_options)

if initial == nil then
initial = false
Expand All @@ -294,7 +302,7 @@ function utils.get_list(str, mode)

return function()
limit = limit - 1
next = vim.fn.searchpos(str)
next = vim.fn.searchpos(str, search_options)

if utils.is_empty_position(next) then
return nil
Expand All @@ -310,7 +318,7 @@ function utils.get_list(str, mode)

while not utils.is_cursor_in_range(next, region) do
limit = limit - 1
next = vim.fn.searchpos(str)
next = vim.fn.searchpos(str, search_options)
if utils.is_empty_position(next) then
return nil
end
Expand Down
10 changes: 10 additions & 0 deletions tests/textcase/plugin/commands/subs_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,16 @@ describe("plugin", function()
"NuncIpsum LoremDolorSit amet",
},
},
-- Test when destination ends with origin
{
keys = ":Subs/FooBar/TestFooBar<CR>",
buffer_lines = {
"FooBar FooBar FooBar",
},
expected = {
"TestFooBar TestFooBar TestFooBar",
},
},
}

for _, test_case in ipairs(test_cases) do
Expand Down