3

For example, wanting to delete the last 3 words from the current line, I press $d3b but I still have the last char from that line not deleted. Is that normal? Is there a better way to achieve what I'm trying to do?

0

4 Answers 4

6

As per Matt's answer, b is an exclusive motion. Using visual mode is a possible way to work around this.

Alternatively, you can also use v as an operator (instead of entering visual mode), like so: $dv3b

See :help o_v, which explains it:

v: When used after an operator, before the motion command: Force the operator to work characterwise, also when the motion is linewise. If the motion was linewise, it will become exclusive. If the motion already was characterwise, toggle inclusive/exclusive. This can be used to make an exclusive motion inclusive and an inclusive motion exclusive.

2

b is an :h exclusive motion, so it behaves this way: "the last character towards the end of the buffer is not included". Make sure you choose appropriate tools.

Note that it's true for the normal mode. In the visual mode everything depends on :h 'selection' option value. So, if set selection=inclusive (default) then $v3bd does what you want.

2

Matt's answer addresses the why, but requires the extra keypress of visual mode to solve your problem. (And there are suggestions that visual mode is less "vim-like", at least when alternatives are available.)

For deleting the last 3 words, one sequence might be $3bD, no longer than your original, where you position first and delete last.

A (much longer) regex oriented solution:

:s/\v(\w+\W*){3}$//
1

The other answers addressed why this happens. One way around this that I prefer is just to use forward motions instead of backwards motions. Because w is an inclusive motion and b is an exclusive motion, in general you can do

bdw

instead of

db

In this particular case since you want to delete from the end of the line, you could use D to delete to the end of line which is a bit shorter:

$3bD

or a more general solution would be

3bd3w
1
  • 1
    w is exclusive. $3bd3w works because it's as special case : last word moved over is at the end of a line . It's documented after :h WORD
    – dedowsdi
    Nov 19, 2019 at 23:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.