This episode demonstrates a few techniques for tidying up whitespace. First, it looks at how to convert between tabs and spaces. Then it shows how to strip trailing whitespace, and finally, how to remove blank lines from a file.
Converting between tabs and spaces
The command for converting between tabs and spaces is:
More specifically, to convert tabs to spaces, run:
:set expandtab :retab!
And to convert spaces to tabs, run:
:set noexpandtab :retab!
Strip trailing whitespace
Strip trailing spaces throughout an entire file by running this substitution command:
This has a couple of side-effects: it moves your cursor, and sets the last item in your search history to trailing whitespace. This function gets around these problems:
function! <SID>StripTrailingWhitespaces() " Preparation: save last search, and cursor position. let _s=@/ let l = line(".") let c = col(".") " Do the business: %s/\s\+$//e " Clean up: restore previous search history, and cursor position let @/=_s call cursor(l, c) endfunction
Put it in your .vimrc file.
If you want to map this function to a key (e.g. F5), add this:
nnoremap <silent> <F5> :call <SID>StripTrailingWhitespaces()<CR>
If you want to run this command automatically when a file is saved, add this:
autocmd BufWritePre *.py,*.js :call <SID>StripTrailingWhitespaces()
Delete blank lines
You can delete all blank lines by running the following command:
- Remove unwanted spaces (on the Vim tips wiki)
- Automatically remove trailing spaces (on Stackoverflow.com)
In the comments, k00pa has posted a method based on
StripTrailingWhitespaces(), which applies Vim’s autoformat command to the
entire file then restores the cursor position. Jonathan Palardy
has recognised that
doesn’t do one thing, it does two (useful) things: saving the “state” and executing a command to remove the trailing whitespace.
He suggests refactoring the methods as follows:
function! Preserve(command) " Preparation: save last search, and cursor position. let _s=@/ let l = line(".") let c = col(".") " Do the business: execute a:command " Clean up: restore previous search history, and cursor position let @/=_s call cursor(l, c) endfunction nmap _$ :call Preserve("%s/\\s\\+$//e")<CR> nmap _= :call Preserve("normal gg=G")<CR>
I do like his choice of key mapping as well. The underscore key is not often
used, so makes for a good alternate
$ key is practically
synonymous with end of line, so it makes for a good mnemonic.
Jonathan goes into a little more detail on his blog. Go read: Preserve: A Vim function that keeps your state.