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.


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.


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(".")
  let @/=_s
  call cursor(l, c)

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.

  • Your source is (probably) vimcast
    – statox
    Feb 15 '17 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. Feb 15 '17 at 8:17
  • 1
    See @Carpetsmoker's answer to a related question for a much simpler version of the function.
    – Rich
    Feb 15 '17 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 =) Feb 15 '17 at 10:06

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.