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 /\s\+$/
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/\s\+$//ge
which may not be recommended, as it'll unconditionally strip trailing whitespace from every file of that type saved by an user saves and there's not a good way to prevent that where trailing whitespace might be desired (which should be rare, but still.)
:h vim-faqand search
/trailing. The hard to memorize tag is
:g/ $/norm $diwseems to do the job. This moves to the end of lines that end with a whitespace and "deletes inside word". Tabs and spaces appear to be considered as a single word, so as long as there is at least one trailing space this does the trick. I may be missing some cases though?
:g/\s$/norm $diwappears to deal with other whitespace characters as well.