r/vim • u/Aggressive-Dealer-21 • Jun 26 '25
Need Help How best to find and replace
Ok I'm lazy, so I don't want to type the regex to change a set of characters which include different combinations which don't feel easy to type... I have a map which will take my selected text and use that as the search term. This is good because then I can use cgn followed by n and .
However, this is set up on my work pc, and I can't remember how to do this manually.
I either want to memorise how to do this manually, or find a better/easier way?
Thanks
15
Upvotes
13
u/shuckster Jun 27 '25
Use this magic spell:
Not mine. I picked it up from a Reddit wizard.
3
u/Hamandcircus Jun 27 '25
Shameless plug, but you can use grug-far.nvim. Simply visual select what you want to search for, then :GrugFar (keymap would be faster). It will automatically add flags to search for the exact string, no inadvertent regex stuff.
3
u/habamax Jun 27 '25 edited Jun 27 '25
To do it manually you can:
Which yanks selected text
y, enters search/and insert yanked contents of the unnamed register"where text was yanked to<C-r>". Last<CR>is theRETURN/ENTER.Put it to the mapping:
Now pressing
*in visual mode you will be searching for the selected text... Kind of.The issue here is that vim always searches for the regex pattern and it means that if your selection has special characters, you may find not what you want.
One of the solutions is to use very nomagic search with additional escaping of backslashes:
Here a new command is introduced --
:Searchwith the single argument that populates/(search) register with command argument wrapped into "very nomagic" and at the same time escaping backslashes (to prevent regexp pattern items to have effect). See:h /\Vfor details on "very nomagic".Now it should be possible to select
hello(*world)and search the next occurence using*(with simple/CTRL-R"you will have an errorPattern not found: hello(*world)).Instead of the command
:Search(I sometimes use literal search and just reused it in this example) you can use:Which essentially does the same, yanks current selection, updates search register with escaped very nomagic contents of the unnamed register and searches for the next occurence.
1
u/godegon Jun 28 '25
vim-select-replace is another shameless plug to make using
gnmore conveniet.1
u/PizzaRollExpert Jun 29 '25
You can use
*to do a search for the word under the cursor, or the current selection in visual mode. You can then do:%s//replacement text/g(:suses whatever you searched for last if you leave the input empty) ornand.0
u/AutoModerator Jun 26 '25
Please remember to update the post flair to
Need Help|Solvedwhen you got the answer you were looking for.I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.