This is quite easy thanks to auto commands. They allow you to specify vimscript to be run when certain events occur in Vim. There are event types for many different things that happen in Vim including loading and exiting/saving a buffer (file).
You'll need something like this in your vimrc.
augroup SpaceFix
autocmd!
autocmd BufReadPost,BufWritePre * :silent %s/\s\+$//ge | :silent %s/\t/ /ge
augroup END
The surrounding augroup
bits aren't strictly necessary but, along with autocmd!
which deletes existing auto commands from the containing group, prevent doubly defining auto commands if you reload your vimrc.
The main line has two events which, from what I am reading in your question, match the occurrences you specified. The following *
indicates that this should be applied for all file types. And following that are two basic substitution commands for deleting trailing space and converting tabs. The pipe character |
is used to separate different commands from each other. The optional but desirable :silent
prefixes prevent both the appearance of X substitutions on Y lines
and the inconvenient necessity of a tap on Return.
One thing that might not be familiar is the e
flag after each substitution. This suppresses errors such as if you don't actually have anything to be substituted in a file.
Update: @Mass mentioned something noteworthy in a comment. The substitution commands will add their patterns to your search history and since this happens for each file load and save you might be bothered by it. If so, :keeppatterns
will prevent it. Insert keepp
before each substitution, e.g. :keepp %s/\s ..etc..
.
Makefile
. Also if you work on other peoples code, they might get upset breaking their layout that works for them. Always check contribution guides. I also highly recommend to watch the first episodes of Vimcasts about handling whitespace in VIM vimcasts.org/episodes/archiveCtrl-Alt-L
or something like that. But for now I am happy with what I got.