Frankie Y. Liu
Frankie Y. Liu

Reputation: 101

Deleting to beginning of line - d0 leaves extra space

I am trying to delete an indented line to the beginning of the line, with d0, but that leaves an extra space that I must delete with x.

The use case is that often I want to insert a blank line between two lines, and yes, I could use 'o' or 'O' and 'Esc' but often I enter insert mode out of habit and enter a line. The autoindent in vim adds a line with extra space (even with smartindent) so I am left with some dangling space that I have to delete with 'd0x'.

The extra 'x' seems awkward given that 'D' deletes to the end of the line leaving no extra space, and yes I could use '0D' to do the same with in one less stroke. But I would like your opinions as to the best approach for this situation. Thanks.

Example

Upvotes: 1

Views: 456

Answers (2)

paxdiablo
paxdiablo

Reputation: 882206

If there's some complicated thing you want to do in vim with minimal keystrokes, the usual approach is to just create a macro for it and bind that macro to a specific key sequence.

For example, for your use case of inserting a blank unindented line, you could just bind to O<ESC>0D (or whatever other key sequence you need). You can test this with the keystrokes (in normal mode, and <ESC> is a single press of the ESC key, not the five individual characters):

qdO<ESC>0Dq

Then just go to some line in your file, enter @d and, voila, an unindented blank line.

To make this permanent, just add it to your vimrc file:

let @d='O<ESC>0D'

where, if you're editing it with vim, ESC can be entered as CTRL-VESC.


Another possibility is to just not worry about indents until some point in the future. By all means, use whatever commands you desire to give yourself a blank line (possibly indented) but either fix that before final write by deleting all trailing tabs and spaces:

:g/[ <TAB>]\+$/s///

or run a script on all files to fix this in a batch operation (even better if this is done as part of automatic pre-checks before source code commit), for example:

find . -name *.cpp -exec sed -iE 's/[ \t]+$//' {} \;

Upvotes: 1

filbranden
filbranden

Reputation: 8898

Addressing the very specific point of why d0 leaves an extra space: The 0 motion is an exclusive motion, which means the last character towards the end of the region is excluded from the operation.

You can use the v modifier to toggle the characterwise motion and make it inclusive:

dv0

This should remove all the characters from the beginning of the line, including the one under the cursor.

Upvotes: 4

Related Questions