To delete all trailing whitespace (at the end of each line), you can use the command:
:%s/ \+$//
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 *.*
Python way:
:py import vim
:pydo vim.current.buffer[linenr - 1] = vim.current.buffer[linenr - 1].strip()
or:
:py import vim
:py for i, l in enumerate(vim.current.buffer): vim.current.buffer[i] = l.rstrip()
Use 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 .vimrc
:
" Removes superfluous white space from the end of a line
function! RemoveWhiteSpace()
:%s/\s*$//g
:'^
"`.
endfunction
There is also DeleteTrailingWhitespace plugin for that.
Highlighting white spaces
To double-check if all trailing spaces are gone, use:
Type / $
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):
:set encoding=utf-8
:set listchars=trail:·
:set list
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 .vimrc
:
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.)
See also:
:h vim-faq
and search/trailing
. The hard to memorize tag is:h faq-12.1
.:g/ $/norm $diw
seems 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 $diw
appears to deal with other whitespace characters as well.