Pasting with overwrite in Vim - vim

I want to be able to paste something from the buffer (probably using p), but instead of inserting it into the text, I want to replace whatever was there before (just like the R command). I've searched Google, vim documentation, and Stack Overflow but could not find anything on the issue. I imagine that it's just a command that I don't know about. Any help would be appreciated.
That's all I need to know, but if you want to know my specific problem:
Essentially I'm just trying to create a short script for documentation headers. At the beginning of every function I put the following:
// FunctionName <><><><><><><><><><><><><><><><><><><><>
However adding all those <> gets annoying. I want to be able to place my cursor on a function name, press the F6 key and it produce the above. The problem, of course, is that function names are not constant sizes and it would make the "chain" look weird. So I just want to paste OVER a bunch of pre-made chain so that the whole thing will always be a constant number of characters. i.e.:
start with
//<><><><><><><><><><><><><><><><><><><><><><><><><><><>
Paste " FunctionName " and end with
// FunctionName <><><><><><><><><><><><><><><><><><><><>

I found a much better solution
R Enter Replace mode: Each character you type replaces an existing character, starting with the character under the cursor.
So R <ctrl-r>" will do what you want. Note there is a space before and after <ctrl-r>".
OLD ANSWER
You can do this with a macro pretty easily
qhmhA <esc>a<><esc>40.80|D`hq
qh start macro
mh set mark
A <esc> insert a space after the existing text
a<><esc> insert '<>'
40. repeat last command 40 times
80| move to column 80
D delete to the end of the line
`h jump back to mark
q end macro
The macro can then be repeated with #h. You probably want to save this to your .vimrc like so
let #h = 'mhA ^[a<>^[40.80|D`h'
Note that the ^[ are supposed to be one character entered by pressing <ctrl-V><esc>

You can use visual selection.
Vp select the whole line and overwrite with buffer
viwp select the word under cursor and overwrite with buffer content.
vi(p overwrite what is in between parenthesis.
I particularly like that it highlights what should be overwritten, which
makes it easier to verify.

You can do it with this:
:exe "normal ".strlen(#p)."x\"pP"
It deletes the right number of chars, and then paste the content of register p.

Short answer
Simply do R and <C-r>0 or the 'register' you are trying to yank. If in doubt, check :reg
Long answer
From :help i_CTRL-R:
Insert the contents of a register. Between typing CTRL-R and
the second character, '"' will be displayed to indicate that
you are expected to enter the name of a register.
The text is inserted as if you typed it, but mappings and
abbreviations are not used. If you have options like
'textwidth', 'formatoptions', or 'autoindent' set, this will
influence what will be inserted. This is different from what
happens with the "p" command and pasting with the mouse.
Special registers:
'"' the unnamed register, containing the text of
the last delete or yank
'%' the current file name
'#' the alternate file name
'*' the clipboard contents (X11: primary selection)
'+' the clipboard contents
'/' the last search pattern
':' the last command-line
'.' the last inserted text
'-' the last small (less than a line) delete
*i_CTRL-R_=*
'=' the expression register: you are prompted to
enter an expression (see |expression|)
Note that 0x80 (128 decimal) is used for
special keys. E.g., you can use this to move
the cursor up:
CTRL-R ="\<Up>"
Use CTRL-R CTRL-R to insert text literally.
When the result is a |List| the items are used
as lines. They can have line breaks inside
too.
When the result is a Float it's automatically
converted to a String.
When append() or setline() is invoked the undo
sequence will be broken.

Related

vim copy paste a block with different line lengths

Is there a way in vim / nvim to block copy paste a set of lines with different lengths.
I want to edit the below text from:
select
date
, impression_cnt
, click_cnt
, like_cnt
from table
to:
select
date
, sum(impression_cnt) as impression_cnt
, sum(click_cnt) as click_cnt
, sum(like_cnt) as like_cnt
from table
I know I can do two separate operations using visual line mode and doing something like
:s/^/sum(
:s/$/) as
However this won't handle the column alias at end.
In VSCode you block enter multiple cursor edit mode and block copy paste the columns, and simple <C-C> and <C-V> and type out max( and ) as in the block mode.
How can I perform this operation without a complex regex that is difficult to remember?
With a single, very simple substitution, assuming the cursor is on the first line to change:
:,+2s/\w\+/sum(&) as &<CR>
The pattern, \w\+, matches one or more "keyword characters", as many as possible, it covers the column names, which are the only part of the lines that need changing,
the & in the replacement part reuses the whole match.
With a manual macro, same assumption:
:,+2norm $ciwsum(<C-v><C-R>") as <C-v><C-r>"<CR>
$ places the cursor on the last character of the line,
ciw cuts the word under the cursor to the default register and enters insert mode,
sum( is just part of the new text you type,
<C-R>" inserts the content of the default register (the <C-v> is used to insert a literal ^R which is needed in this case),
) as is the rest of the new text you type,
and then you insert the column name once again.
Bonus, with the famous "dot formula", same assumption:
$ciwsum(<C-R>") as <C-r>"<Esc>
j.
j.
See :help :range, :help s/\&, :help :normal, :help c, :help iw, :help i_ctrl-r, :help ..
How can I perform this operation without a complex regex that is difficult to remember?
Complex patterns are supposed to be composed on the fly, not remembered so that's not where the problem with complex patterns is. The problem with complex patterns is that it can take time to get them right, which can be a productivity killer.

How to append each line from 11-20 to each line from 1-10 in VIM

I have a file in which first 10 lines are the columns of a table and the rest 10 lines are the values of each column.
How can I use norm in VIM to append the values after each column names like this:
column1
...
column10
value1
...value10
-->
column1: value1
...
column10: value10
It is a little similar with this(Vim - Copy Nth word of each line, from line 10-100, to end of line), but I don't know how to go to line 1:10 and append the copied lines.
Any idea will be appreciated!
Fairly naive and crude way to do this, but:
:1,10norm! 10j0d$10kA: ^[p
Explanation:
1,10norm!: for lines 1 to 10, do the following (the ! means any custom mapping you have will be ignored, thanks to D. Ben Knoble for reminding of this):
10j: move down 10 lines
0d$: delete the whole line (not including newline)
10k: move back up 10 lines
A:: append (at the end of the line) ': ' (note the trailing space)
^[: input escape character, going back to normal mode. This (^[) is a single character and is inputted by typing Ctrl-v then escape, not by typing ^[.
p: paste the line deleted in step 3
Another (copy-pastable) way, (ab)using the substitute command:
:1,10s/\v(.*)\ze(.*\n){10}(.*)/\1: \3/ | 11,20d
which does:
1,10s/: for lines 1 to 10, execute the following substitution:
\v: use very-magic regex mode (see :help \v)
(.*): capture the entire current line (eg column1)
\ze: signal the end of the match. This way everything read (and captured) afterwards will not be affected (but can still be read)
(.*\n){10}: skip 10 (including current) lines, ie skip selector to 10 lines below
(.*): capture the line (eg value1)
/: end the 'select' part of the substitute command
\1: \3: replace with captured groups (eg column1: value1)
|: command separator
11,20d: delete lines 11 to 20
Use blockwise-visual mode to perform the operations.
You can enter visual block mode with Ctrl-V and it allows you to select and operate on columns. It also allows you to perform the same action on a block, which you can use to add the : to the lines with the column names.
I'll use normal Vim syntax for keystrokes in my examples, <C-v> means Ctrl-V.
Start by deleting the values into the default register, using a visual block:
11G<C-v>9j$d
Then Add the : to the column lines, also using a visual block:
1G<C-v>9j$A: <Esc>
Then add some more spaces to the first line, to ensure there's room for all the column names to fit:
A <Esc>
Finally, put the visual block at the end of the first line:
$p
It will actually put it on all lines all the way to the end.
This is slightly different from what you specified, since the values are all aligned on the same column. If you want different spacing, you can perhaps use a :s operation to fix spacing.
10:s/: */: /<cr>
Depending on where you pasted (if some column names had more trailing spaces than the first one), you might have some trailing spaces after the pasted values to fix as well, but that should be easy to do using a similar procedure.
Visual block operations are really powerful, it's a great feature to learn and keep in your "toolbox" in Vim. They're really handy with this kind of problem where thinking in "columns" makes the most sense.

Vim: insert the same characters across multiple lines

Sometimes I want to edit a certain visual block of text across multiple lines.
For example, I would take a text that looks like this:
name
comment
phone
email
And make it look like this
vendor_name
vendor_comment
vendor_phone
vendor_email
Currently the way I would do it now is...
Select all 4 row lines of a block by pressing V and then j four times.
Indent with >.
Go back one letter with h.
Go to block visual mode with Ctrlv.
Select down four rows by pressing j four times. At this point you have selected a 4x1 visual blocks of whitespace (four rows and one column).
Press C. Notice this pretty much indented to the left by one column.
Type out a " vendor_" without the quote. Notice the extra space we had to put back.
Press Esc. This is one of the very few times I use Esc to get out of insert mode. Ctrlc would only edit the first line.
Repeat step 1.
Indent the other way with <.
I don't need to indent if there is at least one column of whitespace before the words. I wouldn't need the whitespace if I didn't have to clear the visual block with c.
But if I have to clear, then is there a way to do what I performed above without creating the needed whitespace with indentation?
Also why does editing multiple lines at once only work by exiting out of insert mode with Esc over Ctrlc?
Here is a more complicated example:
name = models.CharField( max_length = 135 )
comment = models.TextField( blank = True )
phone = models.CharField( max_length = 135, blank = True )
email = models.EmailField( blank = True )
to
name = models.whatever.CharField( max_length = 135 )
comment = models.whatever.TextField( blank = True )
phone = models.whatever.CharField( max_length = 135, blank = True )
email = models.whatever.EmailField( blank = True )
In this example I would perform the vertical visual block over the ., and then reinsert it back during insert mode, i.e., type .whatever.. Hopefully now you can see the drawback to this method. I am limited to only selecting a column of text that are all the same in a vertical position.
Move the cursor to the n in name.
Enter visual block mode (Ctrlv).
Press j three times (or 3j) to jump down by 3 lines; G (capital g) to jump to the last line
Press I (capital i).
Type in vendor_. Note: It will only update the screen in the first line - until Esc is pressed (6.), at which point all lines will be updated.
Press Esc.
An uppercase I must be used rather than a lowercase i, because the lowercase i is interpreted as the start of a text object, which is rather useful on its own, e.g. for selecting inside a tag block (it):
Another approach is to use the . (dot) command in combination with i.
Move the cursor where you want to start
Press i
Type in the prefix you want (e.g. vendor_)
Press esc.
Press j to go down a line
Type . to repeat the last edit, automatically inserting the prefix again
Alternate quickly between j and .
I find this technique is often faster than the visual block mode for small numbers of additions and has the added benefit that if you don't need to insert the text on every single line in a range you can easily skip them by pressing extra j's.
Note that for large number of contiguous additions, the block approach or macro will likely be superior.
Select the lines you want to modify using CtrlV.
Press:
I: Insert before what's selected.
A: Append after what's selected.
c: Replace what's selected.
Type the new text.
Press Esc to apply the changes to all selected lines.
I would use a macro to record my actions and would then repeat it.
Put your cursor on the first letter in name.
Hit qq to start recording into the q buffer.
Hit i to go into insert mode, type vector_, and then hit Esc to leave insert mode.
Now hit 0 to go back to the beginning of the line.
Now hit j to go down.
Now hit q again to stop recording.
You now have a nice macro.
Type 3#q to execute your macro three times to do the rest of the lines.
:%s/^/vendor_/
or am I missing something?
Updated January 2016
Whilst the accepted answer is a great solution, this is actually slightly fewer keystrokes, and scales better - based in principle on the accepted answer.
Move the cursor to the n in name.
Enter visual block mode (ctrlv).
Press 3j
Press I.
Type in vendor_.
Press esc.
Note, this has fewer keystrokes than the accepted answer provided (compare Step 3). We just count the number of j actions to perform.
If you have line numbers enabled (as illustrated above), and know the line number you wish to move to, then step 3 can be changed to #G where # is the wanted line number.
In our example above, this would be 4G. However when dealing with just a few line numbers an explicit count works well.
An alternative that can be more flexible:
Example: To enter the text XYZ at the beginning of the line
:%norm IXYZ
What's happening here?
% == Execute on every line
norm == Execute the following keys in normal mode (short for normal)
I == Insert at beginning of line
XYZ == The text you want to enter
Then you hit Enter, and it executes.
Specific to your request:
:%norm Ivendor_
You can also choose a particular range:
:2,4norm Ivendor_
Or execute over a selected visual range:
:'<,'>norm Ivendor_
Or execute for each line that matches a 'target' regex:
:%g/target/norm Ivendor_
I wanted to comment out a lot of lines in some config file on a server that only had vi (no nano), so visual method was cumbersome as well
Here's how i did that.
Open file vi file
Display line numbers :set number! or :set number
Then use the line numbers to replace start-of-line with "#", how?
:35,77s/^/#/
Note: the numbers are inclusive, lines from 35 to 77, both included will be modified.
To uncomment/undo that, simply use :35,77s/^#//
If you want to add a text word as a comment after every line of code, you can also use:
:35,77s/$/#test/ (for languages like Python)
:35,77s/;$/;\/\/test/ (for languages like Java)
credits/references:
https://unix.stackexchange.com/questions/84929/uncommenting-multiple-lines-of-code-specified-by-line-numbers-using-vi-or-vim
https://unix.stackexchange.com/questions/120615/how-to-comment-multiple-lines-at-once
You might also have a use case where you want to delete a block of text and replace it.
Like this
Hello World
Hello World
To
Hello Cool
Hello Cool
You can just visual block select "World" in both lines.
Type c for change - now you will be in insert mode.
Insert the stuff you want and hit escape.
Both get reflected vertically. It works just like 'I', except that it replaces the block with the new text instead of inserting it.
Suppose you have this file:
something
name
comment
phone
email
something else
and more ...
You want to add "vendor_" in front of "name", "comment", "phone", and "email", regardless of where they appear in the file.
:%s/\<\(name\|comment\|phone\|email\)\>/vendor_\1/gc
The c flag will prompt you for confirmation. You can drop that if you don't want the prompt.
Use Ctrl+V to enter visual block mode
Move Up/Down to 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
Ctrl + v to go to visual block mode
Select the lines using the up and down arrow
Enter lowercase 3i (press lowercase I three times)
I (press capital I. That will take you into insert mode.)
Write the text you want to add
Esc
Press the down arrow
I came here to paste in many lines an already copied string. When copy with y we can paste, in the INSERT MODE, pressing Ctrl+r and right after press ''. This will have the same result as being in NORMAL MODE and press p. This is called paste from registry.
Suppose the following text in the buffer:
vendor_something
text
to_receive
the_paste
pattern
Then we can put the cursor pointing to v in vendor_ and press v, move to right using l until select the underscore symbol we want to paste in the text bellow. After that, we can point the cursor at the beginning of "text" (two lines bellow vendor_something) and press Ctrl+v. Then I to go into INSERT MODE where we press 3j Ctrl+r '' Esc. The result of this sequence will be:
vendor_something
vendor_text
vendor_to_receive
vendor_the_paste
vendor_pattern
:.,+3s/^/vendor_/
Another example, I needed to just add two spaces to a block of 125 lines, so I used (with cursor positioned at the beginning of the first line of the block):
:.,+125s/^/ /
Worked great.
If the change is required in the entire file,
:1,$s/^/vendor_/
If the change is required for only a few lines,
Go to the first line where change is required, and either give the command
:.,ns/^/vendor_/
Substitute n with the line number of the last line in the block.
Or,
:.,+ns/^/vendor_/
Substitute n with number of lines minus 1 in which the change is required.

How to insert a block of white spaces starting at the cursor position in vi?

Suppose I have the piece of text below with the cursor staying at the first A currently,
AAAA
BBB
CC
D
How can I add spaces in front of each line to make it like, and it would be great if the number of columns of spaces can be specified on-the-fly, e.g., two here.
AAAA
BBB
CC
D
I would imagine there is a way to do it quickly in visual mode, but any ideas?
Currently I'm copying the first column of text in visual mode twice, and replace the entire two column to spaces, which involves > 5 keystrokes, too cumbersome.
Constraint:
Sorry that I didn't state the question clearly and might create some confusions.
The target is only part of a larger file, so it would be great if the number of rows and columns starting from the first A can be specified.
Edit:
Thank both #DeepYellow and #Johnsyweb, apparently >} and >ap are all great tips that I was not aware of, and they both could be valid answers before I clarified on the specific requirement for the answer to my question, but in any case, #luser droog 's answer stands out as the only viable answer. Thank you everyone!
I'd use :%s/^/ /
You could also specify a range of lines :10,15s/^/ /
Or a relative range :.,+5s/^/ /
Or use regular expressions for the locations :/A/,/D/>.
For copying code to paste on SO, I usually use sed from the terminal sed 's/^/ /' filename
Shortcut
I just learned a new trick for this. You enter visual mode v, select the region (with regular movement commands), then hit : which gives you this:
:'<,'>
ready for you to type just the command part of the above commands, the marks '< and '> being automatically set to the bounds of the visual selection.
To select and indent the current paragraph:
vip>
or
vip:>
followed by enter.
Edit:
As requested in the comments, you can also add spaces to the middle of a line using a regex quantifier \{n} on the any meta-character ..
:%s/^.\{14}/& /
This adds a space 14 chars from the left on each line. Of course % could be replaced by any of the above options for specifying the range of an ex command.
When on the first A, I'd go in block visual mode ctrl-v, select the lines you want to modify, press I (insert mode with capital i), and apply any changes I want for the first line. Leaving visual mode esc will apply all changes on the first line to all lines.
Probably not the most efficient on number of key-strokes, but gives you all the freedom you want before leaving visual mode. I don't like it when I have to specify by hand the line and column range in a regex command.
I'd use >}.
Where...
>: Shifts right and
}: means until the end of the paragraph
Hope this helps.
Ctrl + v (to enter in visual mode)
Use the arrow keys to select the lines
Shift + i (takes you to insert mode)
Hit space keys or whatever you want to type in front of the selected lines.
Save the changes (Use :w) and now you will see the changes in all the selected lines.
I would do like Nigu. Another solution is to use :normal:
<S-v> to enter VISUAL-LINE mode
3j or jjj or /D<CR> to select the lines
:norm I<Space><Space>, the correct range ('<,'>) being inserted automatically
:normal is probably a bit overkill for this specific case but sometimes you may want to perform a bunch of complex operations on a range of lines.
You can select the lines in visual mode, and type >. This assumes that you've set your tabs up to insert spaces, e.g.:
setl expandtab
setl shiftwidth=4
setl tabstop=4
(replace 4 with your preference in indentation)
If the lines form a paragraph, >ap in normal mode will shift the whole paragraph above and below the current position.
Let's assume you want to shift a block of code:
setup the count of spaces used by each shift command, :set shiftwidth=1, default is 8.
press Ctrl+v in appropriate place and move cursor up k or down j to select some area.
press > to shift the block and . to repeat the action until desired position (if cursor is missed, turn back with h or b).
Another thing you could try is a macro. If you do not know already, you start a macro with q and select the register to save the macro... so to save your macro in register a you would type qa in normal mode.
At the bottom there should be something that says recording. Now just do your movement as you would like.
So in this case you wanted 2 spaces in front of every line, so with your cursor already at the beginning of the first line, go into insert mode, and hit space twice. Now hit escape to go to normal mode, then down to the next line, then to the beginning of that line, and press q. This ends and saves the macro
(so that it is all in one place, this is the full list of key combinations you would do, where <esc> is when you press the escape key, and <space> is where you hit the space bar: qai<space><space><esc>j0q This saves the macro in register a )
Now to play the macro back you do # followed by the register you saved it in... so in this example #a. Now the second line will also have 2 spaces in front of them.
Macros can also run multiple times, so if I did 3#a the macro would run 3 times, and you would be done with this.
I like using macros for this like this because it is more intuitive to me, because I can do exactly what I want it to do, and just replay it multiple times.
I was looking for similar solution, and use this variation
VG:norm[N]I
N = numbers of spaces to insert.
V=Crtl-V
*** Notice *** put space immediate after I.

Why does Vim position the caret one character off with $ (end of line)?

Observe a line in a Vim instance:
Now I hit $:
Why does my cursor not go all the way to the end? Once I try inserting, the text gets inserted before the last character! Even if I try to move right again while still in normal mode I get the bell. Oddly, when in edit mode I can move to the actual end of line with the right arrow key!
Does anyone know why Vim does this? On 7.3 by the way. Thanks for the help.
Pressing $ while in command mode causes the cursor to move to the end of the line, effectively highlighting the last character. Hit i here to insert before the last character, or a to append to the line. It is slightly ambiguous here, because you're using a pipe character as a cursor rather than a rectangular block cursor. Have a look at ":help termcap-cursor-shape" if you want to change that.
If the goal is to append to the end of the line, A will jump to the end of the line and enter insert mode with a single keypress.
Use a to append a character after the current.
Or, to go to the end of the line and append in 1 step, use capital A. I.e. shiftA.
Similarly shift-I to insert at the beginning of the line without first having to press ^.
The cursor can't be between two characters, it is always on a character.
If you press $ then x, you will correctly delete the last printable character of the current line.
What you are observing is the fact that using i, you are always inserting your text before the selected character. If you want to insert after the selected character, you have to use a or better A as it has already been mentioned.
In other words:
i means "insert before character under cursor".
a means "insert after character under cursor".
mnemonic for a : a for "append".

Resources