How to paste in the line where the cursor is? - vim

The command p pastes below the cursor and P pastes above the cursor. What's the command to paste in the line where cursor is?

This all depends on the type of data in the register you're pasting. If the data is line-oriented data (yanked with yy for instance) it will be pasted as a whole line above or below the cursor. If the data is character-oriented (yanked with e.g. y2w) then it will be pasted at or before the cursor position in the current line.
See :help linewise-register for more info on the interaction between the type of register and the put command.

The Edit menu in gvim lists the following:
Paste = "+gP
Put Before = [p
Put After = ]p
If you're running vim in Windows, you can do the following to get Ctrl+C and Ctrl+V to work as expected:
source $VIMRUNTIME/mswin.vim
behave mswin

If you want to keep the current line as it is, you either paste above or below the line.
If you want to overwrite the current line you'll have to delete it first, which means that the following line takes its place, then paste above the new current line.
There are more than one way to do it:
"_ddP
"_dd deletes the whole current line in the "black hole register", the following line is now the current line.
P puts the content of the unnamed register above the current line.
Vp
V puts you in VISUAL LINE mode and selects visually the whole current line
p replaces the selection with the content of the unnamed register
S<C-r>"
S deletes the content of the current line and puts you in INSERT mode
<C-r>" puts the content of the unnamed register
The two last options have an interesting side effect: the content of the previous line is put into the unnamed register which makes it impossible to do multiple pastes with the same content.
Luckily, you can work around this situation:
The "black hole register", mentioned in the first solution works, well… like a black hole. Whatever you put into it disappears forever so you can continue using p and P with some degree of confidence that the unnamed register is still the same from paste to paste.
Vim gives you access to 26 alphabetic registers that you can use to save macros or… paste stuff repeatedly.
Taking the second solution as a starting point, you start by yanking a whole line into register "a with "ayy then you do V"ap on another line.
But all of the above assumes that the text you want to paste is an actual line. Vim makes the difference between "line-wise" and "character-wise" : it won't let you paste a line in a character-wise context or the other way around.
Yanking a whole line with yy keeps its line-wiseness or character-wiseness and you won't be able to p between two characters on a same line. For that you need to make sure that what you yank won't be interpreted as line-wise by Vim. For example, let's assume you are on the first character of the first line and want to yank ipsum dolor and put it at its normal place between lorem and sit:
ipsum dolor
lorem sit amet
You should type "ayee to put your yanked text in register "a, place the cursor where needed and type "aP.

To paste in insert mode you just press Control+R. Then enter the register, e.g. Shift++.
To paste in command mode, you press P, however you've to make sure your line doesn't have a new line character (e.g. yanked by 0v$hy), otherwise it'll appear above the cursor.
The same for visual mode, see: How to paste a line in a vertical selection block? at Vim SE

You can use D to delete from current cursor position to the end of line, and the p to the new cursor position.
That is to cut and paste a whole line use ^D and p.

Shift + v will select the entire line, but you don't want to do that. Instead, press CTRL + v from the beginning of the line which will select by character, then $ to select to the end of the line. yank y and paste p.

I needed to "cast" register contents into a certain (characterwise / linewise / blockwise) mode so often, I wrote the UnconditionalPaste plugin for it. It provides gcp, glp, etc. alternatives to the built-in paste commands that force a certain mode (and by now several more variations on this theme, like pasting with joined by commas or queried characters).
With it, you can just use gcp / gcP to paste after / before the cursor position, regardless of how you've yanked the text.

(I know this thread is old, just leaving this and hope this may help someone)
Inspired by #wbg's comment above regarding deleting the line feed, I added these to my mappings:
nnoremap <leader>p :let #"=substitute(#", '\n\+$', '', '')<CR>p
inoremap <leader>p <esc>:let #"=substitute(#", '\n\+$', '', '')<CR>pa
This is useful when I have a file with some SQLs (line by line) and I have to yank into the code.

vp that's how, type vp in normal mode
How is this not an answer to a 10 year old question, stackoverflow slip'n?
The character under the cursor will be replaced by the the put
To help with and many others scenarios, I've mapped rr for the ability to quickly add a space, or some other 1-off character.
noremap rr i<space><esc>r in my ~/.vimrc

divide the line into 2 wherever you want to insert
paste the section between them
merge the 3 lines with j as described here (Delete newline in Vim)
works, but tedious, and had to think about, look it up
=> vi and emacs are garbage software

I'm not sure there is one. I tried to find documentation and ran across the following three documents:
Vim commands cheat sheet
Vim editor commands
Mastering the VI editor
Unfortunately, all three only have the two commands that you list. Particularly, the third link states that The commands to paste are p and P...

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

Duplicating line in Vim and appending few letters

I am editing a dictionary in a text file, containing Russian words - one word per line.
Some nouns are missing their derivatives, which are usually the same word appended by few more letters - in 6-7 variations as shown in this screenshot:
In Vim I would like to put the cursor in the first column and scroll down line by line. And when I recognize a noun, I'd like to press some (as few as possible!) keystrokes to take that word, copy it in separate lines and append the letters.
I can get rid of the duplicates by issuing %sort u later.
If I could run that command on the whole file it would be something like:
%s/\(.\+\)$/\1^M\1а^M\1ам^M\1ами^M\1ах^M\1е^M\1ном^M/
Do you please have an idea, how to create such a "macro" in Vim?
There are a couple of ways that you can handle this. You can create a macro or you can create a map. Either can be done while running VIM. Either can be placed in another file (your .vimrc, for example, or a file with bindings specific to this project) and sourced when needed.
I will also give you a bit more advice with regular expressions: if you are writing something particularly complex, you can greatly decrease the number of \s needed by starting the regular expression with \v (i.e., :s/\v([0-9a-f]+\s)/0x\1/g).
Creating a Macro in VIM
You can start a macro in VIM by pressing q in Normal mode, followed by the key that you wish to use for the macro. You can then invoke the macro by pressing # followed by the macro's letter. Press q again in Normal mode to stop recording.
You can therefore enter this macro as follows (using the q register):
qq:s/\(.\+\)$/\1\r\1а\r\1ам\r\1ами\r\1ах\r\1е\r\1ном\r/Enterq
Then, when you are on a line and you want to run this command, enter #q from Normal mode.
Storing a macro in a file and sourcing it
When you created a macro in the last step, what you were actually doing was setting the q register. You can check this by entering the registers in command mode. You can instead set this macro in your .vimrc file as follows and it will be available every time you start VIM.
Create the file you want to store this macro in (:new).
Add the following line to the file:
let #q=":s/\\(.\\+\\)$/\\1\\r\\1a\\r\\1b\\r\\1ам\\r\\1ами\\r\\1ах\\r\\1е\\r\\1ном\\r/^M"
(If you yank the line and paste it in VIM with Ctrl+R", there will be a proper ^M character at the end of the line. You'll need to do some manual editing to make sure that it's inside the quotes. Alternatively, you can enter Ctrl+VCtrl+M to enter the ^M character.)
Save the file (:w testmacro.vim).
Source it (:so % or :source %).
Test your macro by typing #q on one of the lines you'd like to do this to.
Later, you will be able to load this macro by running :so testmacro.vim.
Create a Mapping
You can instead create a mapping. The following mapping copies the last word in a given line, pastes it onto the following six lines, and then appends to each of the given lines.
nnoremap <c-j> yy6pAа<esc>jAам<esc>jAами<esc>jAах<esc>jAе<esc>jAном<esc>j
n at the beginning of "nnoremap" indicates that it only functions in Normal mode.
noremap means that this command won't engage in any recursive remapping (whereas with nmap, this could happen).
<c-j> maps to Ctrl+J
yy6p yanks the line and pastes it 6 times.
Aa<esc>j appends to the end of the current line, enters the text (in this case a), exits Insert mode, and moves down a line.
You can enter this command in VIM's command mode or you can store it in a file and load it with the :source command.
Combining Registers with Mappings
You can access a register in your mappings. This means that if you know that entering a given replacement regex will do what you want, you can save that in a register and then enter your command on the current line.
To do this, enter the following commands in a file and then source it:
nnoremap <c-i> :<c-r>f<cr>
let #f="s/\\(.\\+\\)$/\\1\\r\\1a\\r\\1b\\r\\1ам\\r\\1ами\\r\\1ах\\r\\1е\\r\\1ном\\r/^M"
Now you can enter Ctrl+I to run the replacement regex in register f on the current line.
Alternatively, dedicate a few registers to the purpose - let's say a-f.
nnoremap <c-l> yy6p$"apj"bpj"cpj"dpj"epj"fpj
let #a="a"
let #b="ам"
let #c="ами"
let #d="ax"
let #e="e"
let #f="ном
In this case, we're using the ability to press " and the name of a register before hitting a command that uses it, such as paste.
You can record macros by pressing q in the escape mode. For example,
position your cursor on the noun you want to edit.
press qa to start recording macro and store it in register a (other alphabet and digits may also be used for registers) .
do whatever general actions you want to do (copy line, paste, append letters, etc. as in you have tried to show in your search string).
once you are done with the changes, in escape mode press q again.
Your macro is now created in register a. Whenever, you want to repeat your key sequences, just press #a.
Note that you can do anything in recording mode, including any kinds of commands, insertions, cursor movements, and so on. For more information on macros and related options, check out Vim help :h complex-repeat.
Vim registers are shared as place holders for both macros and yanked test; this feature allows you to even save and edit your macros in a file. See this question for details.
Here is a map solution - which copies the line into a buffer and then pastes using p.
The A appends at the end of the line
map <F2> 0dwpo<esc>pAa<enter><esc>pAam<enter><esc>pAax ...etc
If your goal is, when your cursor on a special word, and press something, vim will append different "suffixes" (I hope I used the right word, but you knew what I mean). You could go macro (q). However since you have already written the :s command, you could create a mapping using that command do the same, and it would be shorter.
in command line, you can get the word under cursor by pressing <c-r><c-w>. so you could try:
nnoremap <leader>z :s/<c-r><c-w>/& & &..../<cr>
I didn't write the & & &... part, since I don't know (never tried, I don't have vim under windows. I don't even have windows) if the line break \n could be used here under windows. & means the whole matched part, which in this case is the word under your cursor.
So you just move your cursor to the word, type <leader>z, vim will do the job for you. (if the replacement part is correct :) ).

How to paste yanked text into the Vim command line

I'd like to paste yanked text into Vim's command line. Is it possible?
Yes. Hit Ctrl-R then ". If you have literal control characters in what you have yanked, use Ctrl-R, Ctrl-O, ".
Here is an explanation of what you can do with registers. What you can do with registers is extraordinary, and once you know how to use them you cannot live without them.
Registers are basically storage locations for strings. Vim has many registers that work in different ways:
0 (yank register: when you use y in normal mode, without specifying a register, yanked text goes there and also to the default register),
1 to 9 (shifting delete registers, when you use commands such as c or d, what has been deleted goes to register 1, what was in register 1 goes to register 2, etc.),
" (default register, also known as unnamed register. This is where the " comes in Ctrl-R, "),
a to z for your own use (capitalized A to Z are for appending to corresponding registers).
_ (acts like /dev/null (Unix) or NUL (Windows), you can write to it but it's discarded and when you read from it, it is always empty),
- (small delete register),
/ (search pattern register, updated when you look for text with /, ?, * or # for instance; you can also write to it to dynamically change the search pattern),
: (stores last VimL typed command via Q or :, readonly),
+ and * (system clipboard registers, you can write to them to set the clipboard and read the clipboard contents from them)
See :help registers for the full reference.
You can, at any moment, use :registers to display the contents of all registers. Synonyms and shorthands for this command are :display, :reg and :di.
In Insert or Command-line mode, Ctrl-R plus a register name, inserts the contents of this register. If you want to insert them literally (no auto-indenting, no conversion of control characters like 0x08 to backspace, etc), you can use Ctrl-R, Ctrl-O, register name.
See :help i_CTRL-R and following paragraphs for more reference.
But you can also do the following (and I probably forgot many uses for registers).
In normal mode, hit ":p. The last command you used in vim is pasted into your buffer.
Let's decompose: " is a Normal mode command that lets you select what register is to be used during the next yank, delete or paste operation. So ": selects the colon register (storing last command). Then p is a command you already know, it pastes the contents of the register.
cf. :help ", :help quote_:
You're editing a VimL file (for instance your .vimrc) and would like to execute a couple of consecutive lines right now: yj:#"Enter.
Here, yj yanks current and next line (this is because j is a linewise motion but this is out of scope of this answer) into the default register (also known as the unnamed register). Then the :# Ex command plays Ex commands stored in the register given as argument, and " is how you refer to the unnamed register. Also see the top of this answer, which is related.
Do not confuse " used here (which is a register name) with the " from the previous example, which was a Normal-mode command.
cf. :help :# and :help quote_quote
Insert the last search pattern into your file in Insert mode, or into the command line, with Ctrl-R, /.
cf. :help quote_/, help i_CTRL-R
Corollary: Keep your search pattern but add an alternative: / Ctrl-R, / \|alternative.
You've selected two words in the middle of a line in visual mode, yanked them with y, they are in the unnamed register. Now you want to open a new line just below where you are, with those two words: :pu. This is shorthand for :put ". The :put command, like many Ex commands, works only linewise.
cf. :help :put
You could also have done: :call setreg('"', #", 'V') then p. The setreg function sets the register of which the name is given as first argument (as a string), initializes it with the contents of the second argument (and you can use registers as variables with the name #x where x is the register name in VimL), and turns it into the mode specified in the third argument, V for linewise, nothing for characterwise and literal ^V for blockwise.
cf. :help setreg(). The reverse functions are getreg() and getregtype().
If you have recorded a macro with qa...q, then :echo #a will tell you what you have typed, and #a will replay the macro (probably you knew that one, very useful in order to avoid repetitive tasks)
cf. :help q, help #
Corollary from the previous example: If you have 8go in the clipboard, then #+ will play the clipboard contents as a macro, and thus go to the 8th byte of your file. Actually this will work with almost every register. If your last inserted string was dd in Insert mode, then #. will (because the . register contains the last inserted string) delete a line. (Vim documentation is wrong in this regard, since it states that the registers #, %, : and . will only work with p, P, :put and Ctrl-R).
cf. :help #
Don't confuse :# (command that plays Vim commands from a register) and # (normal-mode command that plays normal-mode commands from a register).
Notable exception is #:. The command register does not contain the initial colon neither does it contain the final carriage return. However in Normal mode, #: will do what you expect, interpreting the register as an Ex command, not trying to play it in Normal mode. So if your last command was :e, the register contains e but #: will reload the file, not go to end of word.
cf. :help #:
Show what you will be doing in Normal mode before running it: #='dd' Enter. As soon as you hit the = key, Vim switches to expression evaluation: as you enter an expression and hit Enter, Vim computes it, and the result acts as a register content. Of course the register = is read-only, and one-shot. Each time you start using it, you will have to enter a new expression.
cf. :help quote_=
Corollary: If you are editing a command, and you realize that you should need to insert into your command line some line from your current buffer: don't press Esc! Use Ctrl-R =getline(58) Enter. After that you will be back to command line editing, but it has inserted the contents of the 58th line.
Define a search pattern manually: :let #/ = 'foo'
cf. :help :let
Note that doing that, you needn't to escape / in the pattern. However you need to double all single quotes of course.
Copy all lines beginning with foo, and afterwards all lines containing bar to clipboard, chain these commands: qaq (resets the a register storing an empty macro inside it), :g/^foo/y A, :g/bar/y A, :let #+ = #a.
Using a capital register name makes the register work in append mode
Better, if Q has not been remapped by mswin.vim, start Ex mode with Q, chain those “colon commands” which are actually better called “Ex commands”, and go back to Normal mode by typing visual.
cf. :help :g, :help :y, :help Q
Double-space your file: :g/^/put _. This puts the contents of the black hole register (empty when reading, but writable, behaving like /dev/null) linewise, after each line (because every line has a beginning!).
Add a line containing foo before each line: :g/^/-put ='foo'. This is a clever use of the expression register. Here, - is a synonym for .-1 (cf. :help :range). Since :put puts the text after the line, you have to explicitly tell it to act on the previous one.
Copy the entire buffer to the system clipboard: :%y+.
cf. :help :range (for the % part) and :help :y.
If you have misrecorded a macro, you can type :let #a=' Ctrl-R =replace(#a,"'","''",'g') Enter ' and edit it. This will modify the contents of the macro stored in register a, and it's shown here how you can use the expression register to do that. Another, simpler, way of modifying a macro is to paste it in a buffer ("ap), edit it, and put it again into the register, by selecting it and "ay.
If you did dddd, you might do uu in order to undo. With p you could get the last deleted line. But actually you can also recover up to 9 deletes with the registers #1 through #9.
Even better, if you do "1P, then . in Normal mode will play "2P, and so on.
cf. :help . and :help quote_number
If you want to insert the current date in Insert mode: Ctrl-R=strftime('%y%m%d')Enter.
cf. :help strftime()
Once again, what can be confusing:
:# is a command-line command that interprets the contents of a register as vimscript and sources it
# in normal mode command that interprets the contents of a register as normal-mode keystrokes (except when you use : register, that contains last played command without the initial colon: in this case it replays the command as if you also re-typed the colon and the final return key).
" in normal mode command that helps you select a register for yank, paste, delete, correct, etc.
" is also a valid register name (the default, or unnamed, register) and therefore can be passed as an arguments for commands that expect register names
For pasting something that is the system clipboard you can just use SHIFT - INS.
It works in Windows, but I am guessing it works well in Linux too.
"I'd like to paste yanked text into Vim command line."
While the top voted answer is very complete, I prefer editing the command history.
In normal mode, type: q:. This will give you a list of recent commands, editable and searchable with normal vim commands. You'll start on a blank command line at the bottom.
For the exact thing that the article asks, pasting a yanked line (or yanked anything) into a command line, yank your text and then: q:p (get into command history edit mode, and then (p)ut your yanked text into a new command line. Edit at will, enter to execute.
To get out of command history mode, it's the opposite. In normal mode in command history, type: :q + enter
For pasting something from the system clipboard into the Vim command line ("command mode"), use Ctrl+R followed by +. For me, at least on Ubuntu, Shift+Ins is not working.
PS: I am not sure why Ctrl+R followed by *, which is theoretically the same as Ctrl+R followed by + doesn't seem to work always. I searched and discovered the + version and it seems to work always, at least on my box.
It's worth noting also that the yank registers are the same as the macro buffers. In other words, you can simply write out your whole command in your document (including your pasted snippet), then "by to yank it to the b register, and then run it with #b.
For context, this information comes from out-of-the-box, no plugins, no .vimrc Vim 7.4 behavior in Linux Mint with the default options.
You can always select text with the mouse (or using V or v and placing the selection in the "* register), and paste it into the command line with Shift + Ctrl + v.
Typing Ctrl + r in the command line will cause a prompt for a register name. so typing :CTRL-r* will place the content register * into the command line. It will paste any register, not just "*. See :help c_CTRL-R.
Furthermore, the middle mouse button will paste into the command line.
See :help->quote-plus for a description of the how X Window deals with selection. Even in a plain, out-of-the-box Vim (again, in Vim 7.4 in Linux Mint, anyway), any selection made with the left mouse button can be pasted in the command line with the middle mouse button.
In addition, the middle mouse button will also paste text selected in Vim into many other X Window applications, even GUI ones (for example, Firefox and Thunderbird) and pasting text into the command line is also possible where the text was selected from other apps.
See :help->x11-selection for addl information.
tl;dr
Try the :CTRL-r approach first, and then use Shift + Ctrl + v or the middle mouse button if you need something else.
It is conceded that it can be confusing.
I was having a similar problem. I wanted the selected text to end up in a command, but not rely on pasting it in. Here's the command I was trying to write a mapping for:
:call VimuxRunCommand("python")
The docs for this plugin only show using string literals. The following will break if you try to select text that contains doublequotes:
vnoremap y:call VimuxRunCommand("<c-r>"")<cr>
To get around this, you just reference the contents of the macro using # :
vnoremap y:call VimuxRunCommand(#")<cr>
Passes the contents of the unnamed register in and works with my double quote and multiline edgecases.
OS X
If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.
Install Vim:
brew install vim --with-lua --with-override-system-vi
Install the GUI version of Vim:
brew install macvim --with-lua --with-override-system-vi
Restart the terminal for it to take effect.
Append the following line to ~/.vimrc
set clipboard=unnamed
Now you can copy the line in Vim with yy and paste it system-wide.
"[a-z]y: Copy text to the [a-z] register
Use :! to go to the edit command
Ctrl + R: Follow the register identity to paste what you copy.
It used to CentOS 7.
If you have two values yanked into two different registers (for example register a and register b) then you can simply set a variable c and do the operation on it.
For example, :set c = str2float(#a) + str2float(#b) and then you can paste the content of c anywhere.
For example whilst in INSERT mode, CTRL + R then type = to enter into the expression register and just type c after equal sign and hit ENTER. Done you should now have the total of a and b registers.
All these can be recorded in a macro and repeated over!
The str2float function is used if you are working with floats, if you don't, you will get integers instead.
I am not sure if this is idiomatic but it worked for my case where I needed to add 2 numbers in a row and repeat it for 500 more lines.
I like to use Control-v to paste from the system clipboard, so I use:
cnoremap <C-v> <C-r>+

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)

How to insert text at beginning of a multi-line selection in vi/Vim

In Vim, how do I insert characters at the beginning of each line in a selection?
For instance, I want to comment out a block of code by prepending // at the beginning of each line assuming my language's comment system doesn't allow block commenting like /* */. How would I do this?
Press Esc to enter 'command mode'
Use Ctrl+V to enter visual block mode
Move Up/Downto select the columns of text in the lines you want to
comment.
Then hit Shift+i and type the text you want to insert.
Then hit Esc, wait 1 second and the inserted text will appear on every line.
For further information and reading, check out "Inserting text in multiple lines" in the Vim Tips Wiki.
This replaces the beginning of each line with "//":
:%s!^!//!
This replaces the beginning of each selected line (use visual mode to select) with "//":
:'<,'>s!^!//!
Note that gv (in normal mode) restores the last visual selection, this comes in handy from time to time.
The general pattern for search and replace is:
:s/search/replace/
Replaces the first occurrence of 'search' with 'replace' for current line
:s/search/replace/g
Replaces all occurrences of 'search' with 'replace' for current line, 'g' is short for 'global'
This command will replace each occurrence of 'search' with 'replace' for the current line only. The % is used to search over the whole file. To confirm each replacement interactively append a 'c' for confirm:
:%s/search/replace/c
Interactive confirm replacing 'search' with 'replace' for the entire file
Instead of the % character you can use a line number range (note that the '^' character is a special search character for the start of line):
:14,20s/^/#/
Inserts a '#' character at the start of lines 14-20
If you want to use another comment character (like //) then change your command delimiter:
:14,20s!^!//!
Inserts a '//' character sequence at the start of lines 14-20
Or you can always just escape the // characters like:
:14,20s/^/\/\//
Inserts a '//' character sequence at the start of lines 14-20
If you are not seeing line numbers in your editor, simply type the following
:set nu
Another way that might be easier for newcomers:
some█
code
here
Place the cursor on the first line, e.g. by
gg
and type the following to get into insert mode and add your text:
I / / Space
// █some
code
here
Press Esc to get back to command mode and use the digraph:
j . j .
// some
// code
//█here
j is a motion command to go down one line and . repeats the last editing command you made.
And yet another way:
Move to the beginning of a line
enter Visual Block mode (CTRL-v)
select the lines you want (moving up/down with j/k, or jumping to a line with [line]G)
press I (that's capital i)
type the comment character(s)
press ESC
This adds # at the beginning of every line:
:%s/^/#/
And people will stop complaining about your lack of properly commenting scripts.
If you want to get super fancy about it, put this in your .vimrc:
vmap \c :s!^!//!<CR>
vmap \u :s!^//!!<CR>
Then, whenever in visual mode, you can hit \c to comment the block and \u to uncomment it. Of course, you can change those shortcut keystrokes to whatever.
Yet another way:
:'<,'>g/^/norm I//
/^/ is just a dummy pattern to match every line. norm lets you run the normal-mode commands that follow. I// says to enter insert-mode while jumping the cursor to the beginning of the line, then insert the following text (two slashes).
:g is often handy for doing something complex on multiple lines, where you may want to jump between multiple modes, delete or add lines, move the cursor around, run a bunch of macros, etc. And you can tell it to operate only on lines that match a pattern.
To insert "ABC" at the begining of each line:
Go to command mode
% norm I ABC
For commenting blocks of code, I like the NERD Commenter plugin.
Select some text:
Shift-V
...select the lines of text you want to comment....
Comment:
,cc
Uncomment:
,cu
Or just toggle the comment state of a line or block:
,c<space>
I can recommend the EnhCommentify plugin.
eg. put this to your vimrc:
let maplocalleader=','
vmap <silent> <LocalLeader>c <Plug>VisualTraditional
nmap <silent> <LocalLeader>c <Plug>Traditional
let g:EnhCommentifyBindInInsert = 'No'
let g:EnhCommentifyMultiPartBlocks = 'Yes'
let g:EnhCommentifyPretty = 'Yes'
let g:EnhCommentifyRespectIndent = 'Yes'
let g:EnhCommentifyUseBlockIndent = 'Yes'
you can then comment/uncomment the (selected) lines with ',c'
Mark the area to be comment as a visual block (<C-V)
and do c#<ESC>p
change it to "#"
put it back
If you do it often, define a short cut (example \q) in your .vimrc
:vmap \q c#<ESC>p
In case someone's multi-line-selection is actually a paragraph, there is no need to manually select the lines. vim can do that for you:
vip: select and mark the whole paragraph
shift-i: insert text at line beginning
escape: leave insert mode/enter normal mode [line beginnings still selected]
escape: unselect line beginnings
Mapping of most voted answer:
1st visual select the desired lines, then execute <leader>zzz, which values:
vnoremap <leader>zzz <C-V>^I-<Space><Esc>
<C-V> to enter visual mode
^ goes to start of line ( or use '0' to 1st non blank)
I to insert in block mode
-<Space> to insert '- ' (for example, edit as you need)
<Esc> to apply same insert to all visual block lines
Or of last visual selection from normal mode:
nnoremap <leader>zzz gv<C-V>^I-<Space><Esc>

Resources