macvim: how to paste several times the same yanked word? - vim

Each time i copy a word and want to replace it for several words, i do:
yank the word
enter visual mode, select the word to be replaced and paste the yanked word.
After this process, the replaced word will be yanked and cannot continue replacing new words bceause i lost the first yanked word. So, i must copy again the first yanked word.
Could anybody guide to me on how to achieve my goal in an efficient way? It could be enough if my yanked word would not get changed.

I would suggest explicitly using a register for your yank and paste.
"ayw or however you chose to yank your word.
"ap to paste.
In this case I've used the a register but you could use whichever suits you.

It has been answered before: Vim: how to paste over without overwriting register.
Overall, crude vnoremap p "_dP mapping will almost get you there, but it won't work well in a few edge cases (e.g. if a word you're replacing is at the end of the line).
The superior approach is to use this crazy-looking snippet (I wish I knew Vimscript at least half as good as the author of this):
" replace visual selection without overwriting default register
function! RestoreRegister()
let #" = s:restore_reg
return ''
endfunction
function! s:Repl()
let s:restore_reg = #"
return "p#=RestoreRegister()\<cr>"
endfunction
vnoremap <silent> <expr> p <sid>Repl()

Personally, I'd favour doing :s/word/replacement words/gc.
Alternatively, you could use "_de to delete the word to be replaced. "_ says use the "black hole" buffer to prevent losing the existing default buffer contents.
Perhaps a bit better than this is to yank the replacement words into an alternative named buffer (e.g. "a3ye), then you can delete the work to be replaced (de) and paste the named buffer "ap.

One addition to #Randy Morris answer: instead of specifying register explicitly in both cases, you can specify it only in the second one, see :h quote0 («Numbered register 0 contains the text from the most recent yank command...»). In this case using a register is better (as it is much easier to type), but if you say you are replacing words, you may want to use ciw<C-r>0 and then one . for each other word you want to replace.

I use this mapping to replace the currently selected text with default register without yanking it:
vnoremap <leader>p "_dP

I dont use yank, but ciw and then repeat with .
For instance:
Go to somewhere inside the word you want to replace.
Do ciw <type new word> Esc
Go to somewhere inside the next word you want to replace.
Press . to repeat the last replace.
Advanced:
You can also first find the word with /<word> and then use ciw <new word>.
Then you dont have to move to the word yourself before pressing . but you can just use n to go to the next (or N to go to the previous).

Related

How to cut and then paste previous item in clipboard in vim?

In vim I copied the string ABCD to my clipboard. Now I want to replace certain words in a paragraph of text by doing c-e (this deletes and immediately puts me in insert mode). But when I paste it will paste the thing I just cut overriding my ABCD.
One solution I came up with is:
c-e
ctrl-o
"0P
But that just seems way too long. Is there a faster alternative to that?
While copying a string, place the cursor at the start of the string, then type
"ayw
where "a means the name of the register(its like a storage) and yw means copy(yank) the word into that register.
There are 26 registers, one for each letter of the alphabet.
When you want to paste the content, type
"ap
where p means to paste. Then use the vim repeat command . to repeat last action
You can store strings in different registers and paste them whenever u want.
to set contents of all registers type
:reg
For more information go to
Using Vim's named registers
Vim registers: The basics and beyond
Vim tips and tricks
You can use yankstack, which simplifies your use case.
This make it easy to cycle against your yank buffer when you paste.
I've personally remapped the keys to space (my leader key).
Here is an extract of my .vimrc:
if &runtimepath =~ 'vim-yankstack'
let g:yankstack_map_keys = 0
nmap <leader>p <Plug>yankstack_substitute_older_paste
nmap <leader>P <Plug>yankstack_substitute_newer_paste
endif
In your case, you just press space p right after having pasted your text. This will replace the word pasted with the last entry in your buffer. You can repeat pressingspace p if you need to go deeper in the history.
Use the "stamping" approach; this allows you to stay in normal mode and is just one keystroke. Add this mapping:
nnoremap S diw"0P
Then press S to "stamp" over any word your cursor is on with what you've yanked.
So, an example of the full routine:
1. ye
2. <move cursor over the word you wish to replace with the yank>
3. S
And, of course, if S is used, chose something else, e.g. ww.
This is a well known approach; see this documentation for variations and details: http://vim.wikia.com/wiki/Replace_a_word_with_yanked_text.
The last thing you yanked is always available in register 0 so, in your case, you only have to do:
<C-e><C-r>0<Esc>
See :help i_ctrl-r.
But yeah, there's a much simpler way for one-off puts:
vep
or, if you need to do those changes several times:
ve"0p

Replace word with contents of paste buffer?

I need to do a bunch of word replacements in a file and want to do it with a vi command, not an EX command such as :%s///g.
I know that this is the typical way one replaces the word at the current cursor position: cw<text><esc> but is there a way to do this with the contents of the unnamed register as the replacement text and without overwriting the register?
I'm thinking by "paste" you mean the unnamed (yank/put/change/delete/substitute) register, right? (Since that's the one that'd get overwritten by the change command.)
Registers are generally specified by typing " then the name (single character) of the register, like "ay then "ap to yank into register a, then put the contents of register a. Same goes for a change command. In this case, if you don't want the text you remove with the change command to go anywhere, you can use the black hole register "_: "_cw. Then once in insert mode, you can hit ctrl-R followed by the register you want (probably ") to put in the contents of that register.
"* - selection register (middle-button paste)
"+ - clipboard register (probably also accessible with ctrl-shift-v via the terminal)
"" - vim's default (unnamed) yank/put/change/delete/substitute register.
Short answer: "_cw^R"
Edit: as others are suggesting, you can of course use a different register for the yank (or whatever) that got your text into the default register. You don't always think of that first, though, so it's nice to do a single change command without blowing it away. Though it's not totally blown away. There are the numbered registers "0 through "9:
Vim fills these registers with text from yank and delete commands.
Numbered register 0 contains the text from the most recent yank command, unless the command specified another register with ["x].
Numbered register 1 contains the text deleted by the most recent delete or change command, unless the command specified another register or the text is less than one line (the small delete register is used then). An exception is made for the delete operator with these movement commands: %, (, ), `, /, ?, n, N, { and }. Register "1 is always used then (this is Vi compatible). The "- register is used as well if the delete is within a line.
With each successive deletion or change, Vim shifts the previous contents of register 1 into register 2, 2 into 3, and so forth, losing the previous
contents of register 9.
Using the information in this post, I have formed this useful mapping. I chose 'cp' because it signifies "change paste"
nmap <silent> cp "_cw<C-R>"<Esc>
EDIT:
Also I took this a step further and supported any motion.
To get the equivalent of command above it would be cpw for "change paste word"
"This allows for change paste motion cp{motion}
nmap <silent> cp :set opfunc=ChangePaste<CR>g#
function! ChangePaste(type, ...)
silent exe "normal! `[v`]\"_c"
silent exe "normal! p"
endfunction
You can use the visual mode of vim for this. e.g. copy a word: ye and then overwrite another one with the copied word: vep
If your cursor is on the word you want to replace with the contents of the unnamed register, you can use viwp. v switches to visual mode, iw selects the inner word, and p puts the contents of the register in its place.
In practice, when I need to replace one word (function name, etc.) with another, I'll move to the one to use as a replacement, yiw to yank the inner word to the unnamed register, then move to the word I'm replacing, and viwp to replace it. Pretty quick way of substituting one word for another. If you searched (/) for the word you're replacing to get to it, you can then just hit n to get to the next occurrence you need to replace. Obviously no substitute for using :%s/find/replace/g, but for a couple of quick substitutions it can be handy, especially if you already have the new word in a register.
If you make use of a named register (ie. use "ay or "ad, etc., to fill your paste register), you can do something like
cw<CTRL-R>a<esc>
Which will replace the word with the contents of register a. As far as I can tell, you can't use the default register because when you cw it'll be filled with the word that was cut by that command.
Do you mean the system paste buffer or the vi register?
If you want to use the system paste buffer then you are fine and could do dw"+P - " chooses a register, and "+ is the system paste buffer.
Otherwise copy into the non-default register with say "ay to copy into register a and then to replace something do dw"aP
You can use yw to yank the word, then you can change the word with yanked word by vipw to yank word and paste previously yanked word.
You can use registers for that:
first place replacement text in register
<mark some text>"ay
where a is register name
then you can use that register in replacement
ve"ap
Or you could do Shift+v-p (select the whole line and paste in its' place)

In VIM, is it possible to use the selected text in the substitute clause without retyping it?

Let's say I have a word selected in visual mode. I would like to perform a substitution on that word and all other instances of that word in a file by using s//. Is there a way to use the highlighted text in the s/<here>/stuff/ part without having to retype it?
Sure. If you selected the word, just "y"ank it, and then type:
:%s/<ctrl-r>"/something else/g
Where is pressing ctrl key with r key, and " is just " character.
All keypresses:
y:%s/<ctrl-r>"/what to put/g<enter>
If you searched for your text before you can use
CTRL-R /
to insert the last search item in your search and replace string.
You can check this page for other similar tricks:
http://www.vim.org/htmldoc/insert.html
You don't have to yank the word, place your cursor on the word and then:
:%s/<C-r><C-w>/bar/g
Another way to access register contents from the command line is via # variables. So if you yank text into the default register, it'll be in a variable called #".
:exe '%s/' . #" . '/stuff/'
Here's a mapping to make this easy to type:
vmap <Leader>s y:exe '%s/' . #" . '//g'<Left><Left><Left>
Now you can highlight something in visual mode, type \s, type your replacement and hit Enter. depesz's version also makes a good mapping (almost exactly as he typed it):
vmap <Leader>s y:%s/<c-r>"//g<Left><Left>

How to emulate Emacs’ transpose-words in Vim?

Emacs has a useful transpose-words command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation.
For example, ‘stack |overflow’ + M-t = ‘overflow stack|’ (‘|’ is the cursor position).
<a>|<p> becomes <p><a|>.
Is it possible to emulate it in Vim? I know I can use dwwP, but it doesn’t work well with punctuation.
Update: No, dwwP is really not a solution. Imagine:
SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) )
// with cursor here ^
Emacs’ M-t would have exchanged b and c, resulting in (a)(c)(b).
What works is /\w
yiwNviwpnviwgp. But it spoils "" and "/. Is there a cleaner solution?
Update²:
Solved
:nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,<CR>kgJ:nohl<CR>
Imperfect, but works.
Thanks Camflan for bringing the %# item to my attention. Of course, it’s all on the wiki, but I didn’t realize it could solve the problem of exact (Emacs got it completely right) duplication of the transpose-words feature.
These are from my .vimrc and work well for me.
" swap two words
:vnoremap <C-X> <Esc>`.``gvP``P
" Swap word with next word
nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> *N*
Depending on the situation, you can use the W or B commands, as in dWwP. The "capital" versions skip to the next/previous space, including punctuation. The f and t commands can help, as well, for specifying the end of the deleted range.
There's also a discussion on the Vim Tips Wiki about various swapping techniques.
In the middle of a line, go to the first letter of the first word, then do
dw wP
At the end of a line (ie the last two words of the line), go to the space between the words and do
2dw bhP
From the handy Equivalence of VIM & Emacs commands
You could add shortcut keys for those by adding something like the following to your vimrc file:
map L dwwP
map M 2dwbhP
In that case, SHIFT-L (in command-mode) would switch words in the middle of the line and SHIFT-M would do it at the end.
NB: This works best with space-separated words and doesn't handle the OP's specific case very well.
There's a tip on http://vim.wikia.com/wiki/VimTip10. But I choose to roll my own.
My snippet has two obvious advantages over the method mentioned in the tip: 1) it works when the cursor isn't in a word. 2) it won't high-light the entire screen.
It works almost like emacs 'transpose-words', except that when transposition is impossible, it does nothing. (emacs 'transpose-words' would blink and change cursor position to the beginning of current word.)
"transpose words (like emacs `transpose-words')
function! TransposeWords()
if search('\w\+\%#\w*\W\+\w\+')
elseif search('\w\+\W\+\%#\W*\w\+')
endif
let l:pos = getpos('.')
exec 'silent! :s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/'
call setpos('.', l:pos)
let l:_ = search('\(\%#\w\+\W\+\)\#<=\w\+')
normal el
endfunction
nmap <silent> <M-right> :call TransposeWords()<CR>
imap <silent> <M-right> <C-O>:call TransposeWords()<CR>
You can use dwwP or dWwP as Mark and CapnNefarious have said, but I have a few notes of my own:
If the cursor is on the first letter of the second word, as in the example you gave, you can use dwbP (or dWbP to handle punctuation);
If the cursor is in the middle of the word, you can use dawbP/daWbP.
There's a transpose-words script on vim.org that works beautifully.

How do I specify "the word under the cursor" on VIM's commandline?

I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type:
:s/\(abc\)/\1\1/
But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef":
:s/\(def\)/\1\1/
How can I write the command in the commandline so that it does this?
:s/\(*whatever is under the commandline*\)/\1\1
While in command-line mode, CTRL+R CTRL+W will insert the word under the cursor.
See the help for c_CTRL-R for a listing of all the other special registers:
:help c_CTRL-R
<cword> is the word under the cursor (:help <cword>).
You can nmap a command to it, or this series of keystrokes for the lazy will work:
b #go to beginning of current word
yw #yank to register
Then, when you are typing in your pattern you can hit <control-r>0<enter> which will paste in your command the contents of the 0-th register.
You can also make a command for this like:
:nmap <leader>w :s/\(<c-r>=expand("<cword>")<cr>\)/
Which will map hitting '' and 'w' at the same time to replace your command line with
:s/\(<currentword>\)/
yiwP
yiw: Yank inner word (the word under the cursor). This command also moves the cursor to the beginning of the word.
P: Paste before the cursor.
You can then map the e.g.: < ALT > - D to this command:
:nmap < ALT >-D yiwP
Another easy way to do this is to use the * command.
In regular mode, when over a word, type
*:s//\0\0<Enter>
* makes the search pattern the current word (e.g. \<abc\>).
:s// does a substitution using the current search pattern, and \0 in the replacement
section is the matched string.
You can then repeat this behaviour, say over word "def", by either typing the same again, or by typing
*#:
#: just repeats the last ex command, without a need for an <Enter>, in this case the substitution.
You can also record a quick macro to do this using the q command
qd*:s//\0\0<Enter>q
Then repeat it to your hearts content by typing
#d
when over a word you want to double. As this is only one character less than the prior solution, it may not be worth it to you - unless you will be doing other ex-commands between the word-doubling, which would change the behaviour of #:
You need to escape the backslashes within the mapping. You can also include the substitution string within the mapping.
:nmap <leader>w :s/\\(<c-r>=expand("<cword>")<cr>\\)/\\1\\1<cr>
ywPx
will do what you describe.
ywPxw
will also advance the cursor to the next word.
#user11211 has the most straightforward way to duplicate the word under cursor:
yiwP
yank inner word (moves cursor to start of word), paste (before cursor).
eg. straigh[t]forward ----> straightforwar[d]straightforward
[] is cursor
To elaborate...
You probably want to have the cursor following your duplicated word:
yiwPea
straigh[t]forward ----> straightforwardstraightforward[]
NOTE:
yiw
is yank inner word (without whitespace)
yaw
is yank all word (including trailing whitespace).
yawPea
is therefore duplicate word including whitespace, and position cursor.
straigh[t]forward ----> straightforward straightforward[]
" count word (case sensitive)
nmap <F4> :%s/\(<c-r>=expand("<cword>")<cr>\)//gn<cr>

Resources