在 Vim 中,替换游标下当前项的所有匹配项

如果在 Vim 中按 *,编辑器将在同一文件中搜索该术语的下一个匹配项。这样你就不用把这个术语打出来了。

有没有一种快速的方法来替换当前在光标下的术语?一个字符发出命令,输入新的术语,然后输入 Enter

19137 次浏览

Just use * and then:

:%s//new value/

If you don't specify a pattern, the substitute command uses the last searched one. Depending on the value of gdefault in your configuration, you might need to add a /g modifier to that command.

You can use:

:%s/<c-r><c-w>/new value/g

where <c-r><c-w> means to literally type CTRL-rCTRL-w to insert the word under the cursor.

In addition to the other answers, you could shave off some more keystrokes by adding following snippet to your .vimrc file for doing a global search and replace.

" Search and replace word under cursor using F4
nnoremap <F4> :%s/<c-r><c-w>/<c-r><c-w>/gc<c-f>$F/i

I went ahead and whipped up a plugin which lets you just enter the following:

:Dr REPLACEVALUE

https://github.com/chiedojohn/vim-dr-replace

Another option is to use gn:

Search forward for the last used search pattern, like with n, and start Visual mode to select the match.
If the cursor is on the match, visually selects it.
If an operator is pending, operates on the match.
E.g., "dgn" deletes the text of the next match.
If Visual mode is active, extends the selection until the end of the next match.
Note: Unlike n the search direction does not depend on the previous search command.

So if you have FOO as last search expression, you can replace its next match with BAR typing cgnBAR<Esc>, and repeat for the following matches with ..

If you want to set the word under the cursor as search expression you can type *N (or *#) to search for the next match and come back.

For example, if your cursor is under the first FOO in this line:

<div class="FOO"><span id="FOO"><b>FOO:</b> FOO</span></div>

and you type *NcgnBAR<Esc>..., you end up with this:

<div class="BAR"><span id="BAR"><b>BAR:</b> BAR</span></div>

It's a feature I also desired! But not only for the word under the cursor, also for a visual selection or a motion.

As a result (and building up on your answers), I added this to my .vimrc:

nnoremap <leader>g :set operatorfunc=SubstituteOperator<cr>g@
vnoremap <leader>g :<c-u>call SubstituteOperator(visualmode())<cr>


function! SubstituteOperator(type)
if a:type ==# 'v'
execute 'normal! `<v`>"my'
elseif a:type ==# 'char'
execute 'normal! `[v`]"my'
else
return
endif


let sub = input("substitute '".getreg("m")."' with ... : ")
execute "%s/".getreg("m")."/".sub."/gc"
endfunction

I can now press things like \sw, \sf; or \si( in normal mode or \s in visual mode and get prompt asking if what I want to substitute my selection with.

(So far I don't know if I want the same prompt as @Lieven...)