2

How can I augment/modify my trailing whitespace logic to also remove any empty or all whitespace lines at the end of a file?

My current whitespace stripping logic in my .vimrc is:

"remove trailing whitespaces automatically                                      
autocmd FileType c,cpp,java,python,markdown,shell autocmd BufWritePre <buffer> %s/\s\+$//e

I've tried Googling for an answer, but only get results that strip the end of the line, not that clean up at the end of the file.

2
  • What did you try?
    – romainl
    Feb 23 at 18:30
  • Do you still have something open in your question? How can we help you further? Otherwise maybe could you accept one of the answers using the v button next to the arrow voting buttons? It allows the question to rest :-) Mar 3 at 15:05

3 Answers 3

2

The following substitution remove the last empty lines:

%s/\_s*\%$//e

The \_s atom match any white space including new line. The \%$ atom match the end of the buffer.

You could do:

autocmd FileType c,cpp,java,python,markdown,shell autocmd BufWritePre <buffer> %s/\s\+$//e|%s/\_s*\%$//e

Or combine both in one substitution:

autocmd FileType c,cpp,java,python,markdown,shell autocmd BufWritePre <buffer> %s/\(\s*$\|\_s\%$\)//e

To avoid that the cursor move to the end of the files when it contains some empty line you could combine it with mkview and loadview to restore the cursor and the scrolling position after the trimming:

autocmd FileType c,cpp,java,python,markdown,shell autocmd BufWritePre <buffer> mkview|%s/\(\s*$\|\_s\%$\)//e|loadview
1

Pretty straightforward solution with VimScript

autocmd BufWritePre <buffer> call deletebufline('%', prevnonblank('$') + 1, '$')
1

With some help from :help [range]:

:$;?\S?+,$delete

The range says from $;?\S?+ (roughly prevnonblank('$'), though with no special casing for the last line containing text) to $ (end of file), execute the deletion.

The address $;?\S?+ says to search backwards from the end of the file for non-whitespace and address the following line.

(This doesn't work for buffers with no trailing blank lines; instead it deletes content after the last row of blanks, even if there's text after that. For that, you probably want something more programmatic like Matt's answer.)

1
  • 1
    @Friedrich thanks for the feedback; I belatedly realized that my "This doesn't work for buffers with no trailing blank lines" wasn't sufficient.
    – D. Ben Knoble
    Feb 27 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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