2

I want all redundant whitespaces to be removed on write/save. How can I do that? By redundant I mean ones that exists after the last character or if there's an empty line and it contains a few whitespaces.

2 Answers 2

5

Probably something like that should work:

autocmd BufWritePre * :%s/\s\+$//

The autocommand triggers :%s/\s\+$// each time a buffer will be written. And the substitution command removes all of the whitespaces at the end of lines.

3

I have a function for this, which also saves the cursor position:

function! <SID>StripTrailingWhitespaces()
  " save last search & cursor position
  let _s=@/
  let l = line(".")
  let c = col(".")
  %s/\s\+$//e
  let @/=_s
  call cursor(l, c)
endfunction

This function can be called on the writepre hook:

autocmd BufWritePre *.rb,*.php,*.py,*.js,*.txt,*.hs,*.java,*.md call <SID>StripTrailingWhitespaces()

Or if you want it on every file:

autocmd BufWritePre * call <SID>StripTrailingWhitespaces()

Note: I have not written this function, but copied it from somewhere. Unfortunaly i don't remember where i found it. As pointed out in the comments, the source is probably vimcast (link). So even if it doesn't matter for you, i don't want to take credit for this function, and vimcast can't be mentioned enough, as it is a great source for vim related knowledge.

4
  • Your source is (probably) vimcast
    – statox
    Feb 15, 2017 at 8:12
  • 1
    @statox i think the source of my source was vimecast ^^. But thanks a lot for the link, i added it to my answer.
    – B.G.
    Feb 15, 2017 at 8:17
  • 1
    See @Carpetsmoker's answer to a related question for a much simpler version of the function.
    – Rich
    Feb 15, 2017 at 9:47
  • @Rich interesting, thank you a lot. It even saves fold and some more stuff, guess i have to adept my preserve function =)
    – B.G.
    Feb 15, 2017 at 10:06

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.