wyc
wyc

Reputation: 55273

Creating a command that replaces the word under the cursor with another one?

I want to create a command that replaces the word under the cursor by another one, say I have the word have under my cursor and it replaces it with the word had and vice versa. How to accomplish that?

Upvotes: 2

Views: 137

Answers (4)

tomas_pribyl
tomas_pribyl

Reputation: 114

If you want to replace all occurrences of the word under the cursor, you can add this into your _vimrc:

" search and replace all occurrences of word under cursor
:nnoremap <C-h> :%s/\<<C-r><C-w>\>/
:inoremap <C-h> <ESC>:%s/\<<C-r><C-w>\>/

Usage of this:

1) Press Ctrl+h (under the cursor is the word "have"), and Vim will enter this in the command line:

:%s/\<have\>/

2) Now just complete the replacing statement:

:%s/\<have\>/had/g

3) And press ENTER...

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172570

The SwapIt - Extensible keyword swapper allows you to configure sets of words (e.g. have and had) and toggle them via <C-a> / <C-x> mappings.

Upvotes: 0

benjifisher
benjifisher

Reputation: 5112

If you actually want to do this with longer words, then this method may help. First, position the cursor on the word "had" and use yiw to yank (copy) it into the @0 register (and also the unnamed register, but we are about to overwrite that). Then move the cursor to "have" and use ciw<C-R>0<Esc> to replace it with the yanked word.

Do not type <C-R> as five characters: I mean hold down the CTRL key and type r. Similarly, <Esc> means the escape key. Do type each as five characters if you want to make a map out of it, for example

:nmap <F2> ciw<C-R>0<Esc>

Upvotes: 3

Bambu
Bambu

Reputation: 548

This could easily be accomplished by ciw and then entering the word that you would like to replace it with. Assuming that you want to replace words with different values.

Another solution is you could use a plugin like switch.vim. You would have to define the words/regular expressions you would want to replace.

Upvotes: 8

Related Questions