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.
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.
Try this:
autocmd BufWritePre * %s/\s\+$//e
if you want to do this for BufReadPre as well you can
keepp %s/\s\+$//e
.
Commented
Mar 31, 2023 at 5:32
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.
One solution is to have a valid .editorconfig
(https://editorconfig.org/) with the appropriate whitespace setting trim_trailing_whitespace
, and an editor like NeoVim 0.9 that supports it. It should remove the whitespace for you.
.editorconfig
to work you probably need a plugin or a special Neovim distribution. It would be good to mention which one. I would personally avoid 'modern' which is an opinion and do not add value to the answer.
Commented
Mar 31, 2023 at 5:28