Revision as of 23:40, May 3, 2013

Contents

Simple commands to remove unwanted whitespace

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:

:%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.

However, this has minor side-effects, such as influencing undo history and sometimes changing scroll position.

Automatically removing all trailing whitespace

One way to make sure to remove all trailing whitespace in a file is to set an autocmd in your .vimrc file. Everytime the user issue a :w command, Vim will automatically remove all trailing whitespace before saving.

autocmd BufWritePre * :%s/\s\+$//e

However, this is a very dangerous autocmd to have as it will always strip trailing whitespace from every file a user saves. Sometimes, trailing whitespace is desired, or even essential in a file so be careful when implementing this autocmd.

One method to mitigate this issue in a .vimrc file, where trailing whitespace matters, is to change how .vimrc prepends wrapped lines. For example, add the following into the .vimrc:

set wrap
set linebreak
" note trailing space at end of next line
set showbreak=>\ \ \

Now when saving the .vimrc it will use "> \" instead of "> " to prepend wrapped lines.

A user can also specify a particular filetype in an autocmd so that only that filetype will be changed when saving. The following only changes files with the extension .pl:

autocmd BufWritePre *.pl :%s/\s\+$//e

Additionally, a FileType autocommand can be used to restrict the autocmd to certain file types only.