Peng Yu wrote:
Hi,
Suppose I want to replace "string1" with "string2" in a file from vim.
1. Highlight "string1" (in visual mode) and then type "y".
2. Highlight "string2" (in visual mode) and then type "p".
However, the problem with the above procedure is that "string2",
instead of "string1", is in buffer. That is if I highlight "string3"
and then type "p", "string3" will be replaced with "string2" instead
of "string1".
I'm wondering if there is any way to avoid change the content in the
buffer?
Thanks,
Peng
First, a bit of terminology:
English terminology: "to replace A by B" means removing A and putting B in its
place, not the opposite.
Vim terminology: A "buffer" contains a whole file being edited. Text being
"yanked" (Vimspeak for "copied"), "deleted" ("cut") or "put" ("pasted") is
held in "registers".
Then, how to do it:
To replace "string2" by "string1" in the (file) buffer while allowing repeated
put of the same (memory) register:
1. Highlight "string1" in visual mode and hit y
"string1" is now in "" (the default register) but also in "0 (the yank
register).
2. Highlight "string2" and hit p (or "0p )
"string1" replaces "string2" in the text; "string2" has now overwritten "" but
not "0 ; it is also in "1 (the top register of the delete list).
3. Highlight "string3" and hit "0p
"string1" replaces "string3" in the text ; "string3" now overwrites "" but not
"0 ; "string2" (the contents of "1 ) is also pushed to "2 , and "string3" goes
into "1
You can use "0p any number of times that way, as long as you do not _yank_
something else.
Alternately, you can memorise something that you want to remember even over
one or more yanks, by placing it in a named register ( "a through "z ):
"by
yanks into register b (also registers " and 0 )
"xd
deletes into register x (also registers " and 1 )
"qp
puts from register q
With yank and delete, using an uppercase letters appends to the register
instead of replacing what is in it; with put, "a and "A are synonymous.
There are other registers: "/ the latest search pattern; "+ the clipboard; "_
the blackhole register (which is always empty; anything deleted to it is _not_
placed in any other register), etc.
See ":help copy-move" and the whole section 5 ("Copying and moving text") of
that helpfile.
The contents of the registers can be remembered across Vim sessions by means
of the viminfo file (see ":help viminfo").
Best regards,
Tony.
--
People who have what they want are very fond of telling people who
haven't what they want that they don't want it.
-- Ogden Nash