Vim Tips Wiki
Register
Advertisement
Tip 479 Printable Monobook Previous Next

created 2003 · complexity intermediate · author johnmaxa · version 5.7


Often I replace one word with another. This is much faster than the substitute command and requires no typing.

For example, to change badName(...) to goodName(...) (with the mappings below):

  • Put the cursor anywhere on goodName and type: gy
  • Move the cursor to badName and type: gp

If there are more than one badNames, type *N before typing go, then n gp to change the next one.

I mapped go to put a space after the word, but someone clever might be able to combine them.

Here is how I mapped the commands:

"replace word with register b WITH SPACE AFTER word
noremap go lb"bPldwi <Esc>hbye

"replace word with reg b WITHOUT SPACE after word
"(lb so no move to previous word, but gives error at end of line)
noremap gp lb"bPldwhbyw

"copy this word to register b for replacing with go and gp
noremap gy lb"bye

Comments[]

Try this

noremap gp heli x<Esc>b"bPldwxbyw

and you can use gp for both words with and without spaces.


" Comment: 'gp' is already assigned by vim
nmap gw lb"wPlcw<Esc>bb
" Word from register w replaces the word under cursor. Use with 'gy'
" After replace, reposition to previous word for possibly another replace.
nmap gy lb"wye
" Yank word into register w.

I usually search for "badName", then do a "cw" (Change word), type "goodName", and then use the "." (repeat last action) to substitute further occurrences.

If the cursor is not at the beginning of "badName", I can always do "bcw" (back-a-word + change word), or "viwc" (change visual-inner-word).


I don't quite understand what this is good for unless you are lucky and have goodName somewhere, where you can jump to really fast. And even then, jumping is context switching and thus slow (on the human's side).

When there's only one thing to change, I do 'ctN' and type 'good' -- or do 'cw', type 'good' and Tab to complete it, depending on the situation.

When there's a few of them, I use '.' to repeat it.

When there's many of them, I do '%s/\<^R^W\>/goodName/gc' or whatever regexp and flags are appropriate.


Advertisement