The following is the functionality I am attempting to implement.
1. What works (normal mode):
- Search/highlight the word the cursor is on.
- Replace the word the cursor is on.
- Note that the word doesn't get erased when I get prompted to replace it, allowing me to make a small correction to the existing word. I obviously have a choice to erase it and input a desired replacement.
vim.keymap.set("n", "<leader>s", "*N")
vim.keymap.set("n", "<leader>r", [[:%s/\<<C-r><C-w>\>/<C-r><C-w>/gI<Left><Left><Left>]])
2. What somewhat works (visual mode):
- Replace all other instances of selected text.
- Here, the word gets erased when I get prompted to replace it. How can I change that so that the behavior is just like in my command for normal mode? I want this behavior in case I just want to make a small modification to a word such as appending something or changing a letter.
vim.keymap.set("v", "<leader>r", [["hy:%s/<C-r>h//g<Left><Left>]])
EDIT
The solution to this part was offered by Vivian De Smedt. The keymap that leads to the desired result is:
vim.keymap.set("v", "<leader>r", [["hy:%s/<C-r>h/<C-r>h/gI<Left><Left><left>]])
3. What doesn't work (visual mode):
- Search/highlight all other instances of selected text.
- Here it seems like my command from normal mode gets activated, and only the word the cursor is on gets highlighted instead of whatever was selected in visual mode. How can I fix this?
vim.keymap.set("v", "<leader>s", "*N")
The GIF below illustrates this problem. Doing <leader>s
while in normal mode searches for the word the cursor is on (the first two demos in the GIF). That is the desired behavior. In visual mode, however, instead of performing the search on the whole selection, it still only searches the word the cursor is on (the third demo in the GIF). That is not what is desired. In that particular example, it should have searched for vim.key
not keymap
.
EDIT
The solution to this part was also offered by Vivian De Smedt. The keymap that leads to the desired result is:
vim.keymap.set("v", "<leader>s", [["hy:let @/=@h<CR>nN]])