Today I learned: How to delete until the beginning of the line including the cursor in Vim
Posted on
Five years I have been using Vim, as well as consumming various content about it such as blogs, books, screencasts, forums... Five years and I never came across this single character that may make a difference.
Inconvenience
Note: In the below text snippets, the square brackets symbolise the cursor, and the character inside these brackets, the character being under the cursor.
Let's say you have the following text snippet, and that you are in normal mode:
Today is[:]Tuesday
Now you want to delete backward until the beginning of the line.
First things that come in mind are usually the commands d^
, d|
or d0
.
But unfortunately, here is what you are left out with:
[:]Tuesday
As you can see the character previously under the cursor is still present. This does not meet the original expectation.
The reason
The reason behind this, is that the motions used above, ^
, |
and 0
are
defined as exclusive
in Vim.
According to Vim documentation:
A character motion is either
inclusive
orexclusive
. Wheninclusive
, the start and end position of the motion are included in the operation. Whenexclusive
, the last character towards the end of the buffer is not included.
In our example the "last character towards the end of the buffer" is the :
,
therefore it is not deleted.
The solution
Hopefully, Vim has a mean to turn an exclusive
motion into an inclusive
motion (and vice-versa), using the v
modifier.
Here are the inclusive
equivalent of the above presented commands:
dv^
, dv|
and dv0
.
Now applying one of these commands to the first text snippets produces the following:
Tuesday
Bingo!
Beyond deletion
Since the behaviour comes from the nature of the motion rather than the
operator, this can be applied to other operations too, such as change
(c
) or
yank
(y
).
Below, is the use case of willing to change Today is: Tuesday
to Yesterday was Tuesday
, starting with the text snippet and the cursor positioned on the :
:
Today is[:]Tuesday
Now, type the sequence: cv0Yesterday was
and then Escape
. Now you should end up with:
Yesterday was Tuesday
How to tell a motion is exclusive or inclusive?
In the Vim documentation, for each motion description, it provides its nature.
For instance here is the excerpt for the 0
motion:
0βββTo the first character of the line. exclusive motion.