Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why vim pasting behaves differently depending on yanking method

Tags:

vim

paste

yank

I see different pasting behaviour depending on how I yanked a line. I would like to know why.

If I yank a line starting from normal mode:

^v$y

^ to go to the beginning of the line

v to enter visual mode

$ to go to the end of the line

y to yank

Then I use p to paste and it works as expected.

However, when I yank a line starting from normal mode and using visual mode linewise:

Vy

V to go to visual mode linewise

y to yank

And then I use p to paste, I see that the line is pasted below the current line. It is like paste operation is opening a new line first and then pasting there.

Example. Lines at the beginning:

Line1
Line2
Line3. Insert here 

I yank Line2 using method 1.

I move the cursor to the dot of Line3 and press p to paste. I get this result:

Line1
Line2
Line3.Line2 
 Insert here

But when I do the same thing using yanking method two I get this result:

Line1
Line2
Line3. Insert here
Line2

If the contents of the :registers are the same in both cases why pasting works different?

Edit:

Found the answer here

Even if the register contents are the same; the type of register becomes different depending on the yanking method and different register type makes pasting do a different thing.

like image 501
Robert Avatar asked Mar 05 '23 03:03

Robert


1 Answers

Explanation

If you look closely, you should see a difference on whether you've used v$ or V:

:registers ab
--- Registers ---
"a   foo
"b   foo^J

That ^J is the newline character that signifies that the entire line has been yanked.

Motions either affect whole lines, or the characters between the start and end position. Inside Vim, this is called :help linewise and characterwise. The same applies to visual mode (and there's a third mode for <C-V> called blockwise). So, it makes a difference how you yank stuff! You see this in the :registers command, and can also query this via the :help getregtype() function, but in practice, this rarely comes as a surprise (once you've grasped the concept).

Power up with plugins

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 (e.g. from linewise visual mode via V, as in your question).

like image 103
Ingo Karkat Avatar answered Apr 05 '23 22:04

Ingo Karkat