5

I've been doing this:

au BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif

The problem is that it moves the cursor sometimes when I save the file.

6

Try this:

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

if you want to do this for BufReadPre as well you can

https://stackoverflow.com/questions/356126/how-can-you-automatically-remove-trailing-whitespace-in-vim

| improve this answer | |
3

One option is something like this:

" ~/.vim/plugin/whitespace.vim
function! s:trim_trailing_whitespace() abort
  let l:view = winsaveview()
  keeppatterns %substitute/\m\s\+$//e
  call winrestview(l:view)
endfunction

augroup trim_spaces
  autocmd!
  autocmd BufWritePre * call <SID>trim_trailing_whitespace()
augroup END

Where we save and restore the view to keep the cursor position.

| improve this answer | |

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.