Tolga Kurt
Tolga Kurt

Reputation: 85

Unintuitive behavior of p in Vi/Vim

In Vim, when we try to paste the last yank, we press p. At that point, I expect the register to be pasted where my cursor is, not after the cursor.

To be more precise, it behaves like 'a' which is a special version of 'i'. But 'p' is such a primitive command that I expect it to behave like 'i' instead of 'a'.

At the cursor - After the cursor
i - a
P - p

Bonus question: Why is i+<esc>=h ?

Upvotes: 0

Views: 247

Answers (2)

romainl
romainl

Reputation: 196777

You are confused: none of those commands work "at the cursor" because, in normal mode, the cursor is always on a character. Pasting "at the cursor" or entering insert mode "at the cursor" would mean that the character under the cursor should be removed which is rarely what we want and the behavior of iapP is consistent with that.

i doesn't start insert mode "at the cursor" but "before the cursor" and P follows the same logic: the content of the unnamed register is inserted "before the cursor".

lore[m] ipsum
i
lore|m ipsum <-- before the cursor

a starts insert mode "after the cursor" and p follows the same logic: the content of the unnamed register is inserted "after the cursor".

lore[m] ipsum
a
lorem| ipsum <-- after the cursor

However, Vim would suck if it wasn't possible to paste over existing text (v{motion}p) or starting insert mode while removing the character under the cursor (s) or all kinds of crazy text-manipulation tricks.

To get the most out of Vim, you must embrace modality and — more specifically — get used to the behavior of the cursor in normal mode.

Bonus answer: when you exit insert mode, the normal mode cursor position is always placed on the character to the left of the insert mode cursor. This is a semi-arbitrary choice that kind of makes sense and the opposite behavior (put the cursor on the right) wouldn't make much more sense IMO.

Upvotes: 5

Ingo Karkat
Ingo Karkat

Reputation: 172698

It's hard to argue with intuition - everybody has his own :-)

The reason for the behavior of p is the same as for a: You need a way to paste after the text. Otherwise, it wouldn't be possible to do this at the end of the line (ignoring newer Vim settings such as 'virtualedit', which did not exist in old vi), and elsewhere you'd have to move the cursor (cumbersome!) before the paste.

On moving left

Likewise, the cursor moves left after Esc so that it is always positioned on a valid character. See this Vim Tips Wiki page for more details and remedies.

Upvotes: 5

Related Questions