There is a phrase that I want to look for in Vim. When found, I want to delete that occurrence of the phrase. What is the easiest way to cycle through all the occurrences (via <
1. In my opinion, the most convenient way is to search for one
occurrence first, and then invoke the following :substitute
command:
:%s///gc
Since the pattern is empty, this :substitute
command will look for
the occurrences of the last-used search pattern, and will then replace
them with the empty string, each time asking for user confirmation,
realizing exactly the desired behavior.
2. If it is a common pattern in one’s editing habits, one can further define a couple of text-object selection mappings to operate specifically on the match of the last search pattern under the cursor. The following two mappings can be used in both Visual and Operator-pending modes to select the text of the preceding match of the last search pattern.
vnoremap i/ :call SelectMatch()
onoremap i/ :call SelectMatch()
function! SelectMatch()
if search(@/, 'bcW')
norm! v
call search(@/, 'ceW')
else
norm! gv
endif
endfunction
Using these mappings one can delete the match under the cursor with
di/
, or apply any other operator or visually select it with vi/
.