7

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.

1

3 Answers 3

8

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

1
  • FWIW this clobbers the search pattern. If you want to keep the search pattern unchanged, you can use keepp %s/\s\+$//e.
    – Hoblovski
    Mar 31 at 5:32
4

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.

0

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.

7
  • 1
    I suspect your solution is unclear to most :-) For .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. Mar 31 at 5:28
  • @VivianDeSmedt That's why I said NeoVim 0.9, which has support built-in.
    – Neil G
    Mar 31 at 5:53
  • @VivianDeSmedt As for modern, it is an opinion, but the idea is that most editors are moving to support it. And it's a lot more of an elegant (also an opinion) solution that the buffer-write hook.
    – Neil G
    Mar 31 at 5:58
  • 1
    @VivianDeSmedt no worries, just trying to add a helpful answer to steer people to move to better solutions. I wish I had known about editor-config before. And that said, my opinion about what's "modern" doesn't prevent other people from making their own decisions :)
    – Neil G
    Mar 31 at 6:32
  • 1
    Given that the validity of "modern" in this context can change as the answer ages, I've opted to edit it away. The answer will stand on its merit as a solution to the problem and not on how new it is. That said, community drives consensus here. So if the majority feel the characterisation is important or necessary, it should stand.
    – D. Ben Knoble
    Apr 1 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.