David542
David542

Reputation: 110093

Delete trailing whitespace, alternative to substitute command

To delete trailing whitespace on a line or across a file I can do:

:[range]s/\s\+$//

However, I was wondering for a single line in normal mode if there's an easier approach, for example if the line is:

Hi, I am a line           |

And my cursor is past the e, is there a more generic command than doing dTe in normal mode? The next best I could find was dg_, but that goes one too far. And then, one more option might be gElD.

Upvotes: 2

Views: 1674

Answers (1)

rkta
rkta

Reputation: 4579

Generic way without :substitute

Use diw to delete multiple whitespace (including tabs) while the cursor is on one of the whitespaces (like in the example).

This works for any whitespace sequence: trailing, leading, etc.

Use dw to delete from the cursor to the end of the sequence. This is useful when you want to re-indent a line or fix alignment.

As this is independent of the first/last character of the previous/next word this is the most generic way.

Using a mapping with :substitute

Use nmap <leader>tr :%s/\s\+$// to remove all trailing whitespace in the whole buffer by pressing \tr (assuming the original mapleader)1.

Replace tr with what ever suits you best.

Omit the the % in the mapping to make it only work on the current line.

--

As a side note: Use set list listchars=trail:· to show trailing whitespace (replace · with any character you like).

--

1 Removing all whitespace may not be what you want, especially when using a version control system and the file contains whitespace not added by yourself.

Upvotes: 2

Related Questions