From: http://vim.wikia.com/wiki/Remove_unwanted_spaces
In a search, \s
finds whitespace (a space or a tab), and \+
finds one or more occurrences.
Delete all trailing whitespace (at the end of each line) with: Edit
:%s/\s\+$//
Like with ed(1), the substitution text can be omitted if blank:
:%s/\s\+$
More rarely, a user might want to delete (leading) whitespace at the beginning of each line:
:%s/^\s\+ " Same thing (:le = :left = left-align given range): :%le
With the following mapping a user can press F5 to delete all trailing whitespace. The variable _s
is used to save and restore the last search pattern register (so next time the user presses n
they will continue their last search), and :nohl
is used to switch off search highlighting (so trailing spaces will not be highlighted while the user types). The e
flag is used in the substitute command so no error is shown if trailing whitespace is not found. Unlike before, the substitution text must be specified in order to use the required flag.
:nnoremap <silent> <F5> :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar>:nohl<CR>
See Highlighting whitespaces at end of line to display, rather than delete, unwanted whitespace.