3

I have text in my buffer like this:

foo
bar
baz

and my cursor is on the "f" of foo.

Let's say I want to delete up-to-and-including the "a" in bar.

So in normal mode I try: d/ba<enter>

So this is invoking the delete command, then doing a forward search for "ba" and pressing enter.

I would expect this to delete up to the "r" in bar, basically including the search match in the deletion.

But, it just deletes the "foo" line, leaving "bar" in-tact, with the cursor at the start of the "bar" line.

I understand there are many other ways to accomplish this particular situation, but I am trying to understand this fundamental behavior.

Why is this occurring, and how can I use the / command so that it deletes/yanks/etc including the match?

1
  • 4
    d/ba/e<enter> - see :h search-offset. Why? Because / is an exclusive motion.
    – VanLaser
    Nov 29, 2015 at 20:43

1 Answer 1

5

Add \zs to the end of the search pattern. This will make it so that everything before \zs will be excluded from the actual match, but it is required to be there. The counterpart of \zs is \ze, which excludes everything after it from the match but requires it to be there.

For more help on \zs, see :help \zs.

As mentioned in VanLaser's comment, you can also use a search-offset to accomplish this. In you example, the command would be /ba/e<enter>, since the e offset has the effect of making the search an inclusive motion, thus deleting the match with the rest of the characters between it and the cursor.

For more on search offsets, see :help search-offset.

2
  • how does this differ from using /e (as shown in @VanLaser's answer. Both seem to work Nov 29, 2015 at 20:51
  • 1
    It differs in that this is using a trick of vim's regex system, whereas VanLaser's is using a feature of vim's search capability. Nov 29, 2015 at 20:54

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.