To delete all trailing whitespace (at the end of each line), you can use the command:
To include tabs, use
\s instead of space.
From the command-line:
$ ex +'%s/\s\+$//e' -cwq file.c
All the files in the current directory (recursively use
$ ex +'bufdo!%s/\s\+$//e' -cxa *.*
:py import vim
:pydo vim.current.buffer[linenr - 1] = vim.current.buffer[linenr - 1].strip()
:py import vim
:py for i, l in enumerate(vim.current.buffer): vim.current.buffer[i] = l.rstrip()
lstrip() for left strip (trailing),
rstrip() for right strip (leading) or
strip() to remove from both ends.
Here is useful function which removes superfluous white space from the end of a line which you can add to your
" Removes superfluous white space from the end of a line
There is also DeleteTrailingWhitespace plugin for that.
Highlighting white spaces
To double-check if all trailing spaces are gone, use:
/ $ to find them. If there are some, vim would highlight them for you.
Use colours to highlight them:
:highlight ws ctermbg=red guibg=red
:match ws /\s\+$/
Use visible characters (source):
See also: Highlight unwanted spaces
To highlight trailing whitespace by default, you may configure your
.vimrc as follow:
highlight ws ctermbg=red guibg=red
match ws /\s\+$/
autocmd BufWinEnter * match ws / \+$/
Removing white spaces by default
If you would like to make sure that all trailing whitespace in a file are removed automatically on save, you may add the following command into your
autocmd BufWritePre *.c,*.php :%s/ \+$//ge
which is not recommended, as it'll strip trailing whitespace from every file a user saves (even where whitespace can be desired).