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.
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.