Skip to content

Commit

Permalink
fix: suppress "no more pattern" messages
Browse files Browse the repository at this point in the history
If you start at the first occurrence of a search word in a buffer then
get to the end and the substitution command repeats from the top there
is no more occurrence of the word and so throws an error.

Let's try to suppress that error by only doing the second substitution
from the fist line to the line above the cursor position if that search
word exists.

Again, this is a lot of code for such a nicety of not jumping to the top
of a file during a search/replace. Time will tell if it's worth it.

There remain issues:

- the words above the cursor don't highligh with the Substitute highlight
  group.
- they do highlight after you press enter to start substitution, which is
  also odd
- the message after the first substitution is correct, e.g. replaced 3
  words on 3 lines, but the second one doesn't occur and makes the first
  one wrong since you just replaced more words!
  • Loading branch information
wassimk committed May 27, 2024
1 parent f7bf242 commit b938ac3
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions plugin/scalpel.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,33 @@
-- scalpel.lua
--

local function word_exists_above_cursor(word)
local current_line = vim.api.nvim_win_get_cursor(0)[1]
for i = current_line - 1, 1, -1 do
local line = vim.api.nvim_buf_get_lines(0, i - 1, i, false)[1]
if string.find(line, word) then
return true
end
end
return false
end

local function substitute_current_word()
local word = vim.fn.expand('<cword>')
local pattern = ':,$s/\\v(' .. word .. ")//gc|:undojoin|1,''-&&"
local substituation_command_down = ':,$s/\\v(' .. word .. ')//gc'
local repeat_from_top_to_current_line = "|1,''-&&"
local cursor_move_to_replace_pattern

if word_exists_above_cursor(word) then
substituation_command_down = substituation_command_down .. repeat_from_top_to_current_line
cursor_move_to_replace_pattern = '<Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left>'
else
cursor_move_to_replace_pattern = '<Left><Left><Left>'
end

local cursor_move = vim.api.nvim_replace_termcodes(
'<Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left>',
true,
false,
true
)
local cursor_move = vim.api.nvim_replace_termcodes(cursor_move_to_replace_pattern, true, false, true)

vim.api.nvim_feedkeys(pattern .. cursor_move, 'n', true)
vim.api.nvim_feedkeys(substituation_command_down .. cursor_move, 'n', true)
end

vim.keymap.set('n', '<leader>e', substitute_current_word, { desc = 'Substite current word in file' })

0 comments on commit b938ac3

Please sign in to comment.