How do I delete till non-whitespace in vim?

Viewed 27373

I'm looking for a command to delete from the cursor to the first non-whitespace character on the same line. I've googled for a while and tried several possibilities. No joy. Does someone out there know how to do this?

6 Answers

Many of the answers here don't really address the question directly. The asker wants to know how to delete up to the first non-whitespace character. Some of the answers will technically work, but let's take a look at how to do this explicitly.

The following examples demonstrate how to do this in normal mode with variations that account for the starting position of the cursor. The u̲nderlined c̲haracters indicate the cursor position:


     dw:   foo_     bar   →   foob̲ar

The delete word command, described in other answers, works just fine to delete up to the next non-whitespace character when our cursor is positioned before the target.


     db:   foo      b̲ar   →   b̲ar

Naturally, we'd want to try the inverse of dw to delete backwards to the first non-whitespace character before the cursor. However, as shown above, the delete back-word command deletes more than we expect—it erases the previous word as well. For this case, we should use:

     dT<?>:   foo      b̲ar   →   foob̲ar

...where <?> is the first non-whitespace character before the cursor. The delete back-unTil command erases everything up to but not including the character <?>, which, in this case, is the character o at the end of "foo".


     dt<?>:   foo_     bar   →   foob̲ar

Similar to the previous command, we can use delete until (with a lowercase "t") to delete characters forward until the next <?> character (the b in "bar", for this example). This achieves the same result as dw for the purpose of this question.


     diw:   foo   _   bar   →   foob̲ar

If our cursor is positioned in the middle of the whitespace, we can use the delete inner word command to remove the whitespace from both sides.


     d/<?>:   foo_   \n   bar   →   foob̲ar

If the whitespace we want to remove includes line-breaks, we can use the command shown above to delete until matched pattern of <?>, where the pattern in this case is just the first non-whitespace character. As shown, press Enter to complete this command.

When the first non-whitespace character occurs at the beginning of the line after the break, Vim will remove the whitespace, but leave the target on the next line. We need to add J to the above command to Join the lines (an uppercase "j").

     d/<?>J:   foo_     \nbar   →   foob̲ar

d W will delete word include the last space. If the word you want to delete is at the end of a line, you can prefer use d e. because if you use d W, it can shift your next line up.

I always use d i W.

Related