5

Vim automatically strips trailing whitespace from my files on save, which is extremely annoying in various contexts. How do I disable this behaviour?

This question is not a duplicate of this one, because I'm not using editorconfig at all. This behaviour has been the default in every version of Vim I've ever used, including MacVim, NeoVim, and the build of Vim 8.1 I compiled myself.

1
  • 5
    No version of Vim does that by default. I think you added this to your vimrc (or maybe you copied someone else's vimrc) without realizing. Your best bet is to read our famous how do I debug my vimrc question :)
    – statox
    Commented Feb 5, 2019 at 13:39

2 Answers 2

4

In my .vimrc I have the following function:

" Trim trailing whitespace
" ========================
function! TrimWhitespace()
  " trailing whitespaces have meaning in markdown so don't try there
  if &filetype!='markdown'
    let l:save = winsaveview()
    %s/\s\+$//e
    call winrestview(l:save)
  endif
endfunction

command! TrimWhitespace call TrimWhitespace()

This checks if the current file is a markdown file, and disables the removal of trailing whitespace if it is. You can expand this for other filetypes.

5
  • Instead of putting that in your vimrc and then checking the filetype you should put your code in a ` ftplugin` (e.g. ~/.vim/after/ftplugin/markdown.vim ) and make the command buffer local. See :h ftplugin and :h :command-buffer.
    – statox
    Commented Feb 6, 2019 at 8:37
  • @statox After reading vimways 2018-3 I did something different. I put it in .vim/plugin/trim_whitespace.vim. However this has lived in my vimrc for several years and worked flawless.
    – PeterVP
    Commented Feb 6, 2019 at 12:59
  • I was recommending the ftplugin because it makes more sense to make the command only available for the filetype you want rather than checking that directly in the function. But making it a plugin is also a correct solution: whatever floats your boat ;)
    – statox
    Commented Feb 6, 2019 at 13:44
  • @statox The check for filetype is negative (all but markdown), so I don't think an ftplugin would have worked... Right?
    – filbranden
    Commented Feb 6, 2019 at 14:34
  • Oh yes totally I read it too fast and didn't see the ` !` , my comments were completely off topic, sorry for that.
    – statox
    Commented Feb 6, 2019 at 15:28
2

@statox was right on the money: it was, of course, an old leftover in my .vimrc. Who would have guessed!

2
  • Could you write a sentence or two how to find the autocmd that causes this? I guess you did :verbose autocmd BufWritePre.
    – Ralf
    Commented Feb 5, 2019 at 15:43
  • Nothing as smart as that. I just deleted huge swaths of my .vimrc until I stopped seeing the behaviour, then visually searched the responsible section.
    – henrebotha
    Commented Feb 5, 2019 at 15:49

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