3

This is a noob attempt of mine, to remove trailing spaces in a file. The first attempt is:

:%normal g_lD

It worked, and I was happy. Then I tried it on a single line where there was no trailing whitespace using normal mode command

g_lD

Not too surprisingly, this deleted the last valid,non-blank character of the line since there is no trailing whitespace on this line.

Now my question is this -

why did my first command succeed on all lines?

(it did not delete the last non-blank characters on all those lines with no trailing whitespace)

1
  • 2
    Here’s an alternative solution for deleting trailing white space: :%s/\s\+$
    – Rich
    May 12 at 18:23
3

See the last sentence in :help :normal:

Execution stops when an error is encountered.

In this context, trying to go right at the end of the line is considered an error, so the D isn’t carried out.

This "stop on error" behaviour is also visible in various other places where Vim plays a macro. e.g. mappings, recordings.

In particular, it's useful for terminating a recursive macro when it's done all its work.

If for some reason you need execution to continue when errors occur, you can use :silent!, which will cause Vim to ignore the errors and carry on executing the keystrokes:

3
  • Thanks a lot! Finally, one less burden of my unresolved curiosities. May 12 at 18:22
  • 1
    is it worth pointing out that :silent! normal negates this behavior?
    – Mass
    May 12 at 23:04
  • @Mass It's worth pointing it out to me! (I wasn't aware of this.)
    – Rich
    May 13 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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