Learn Vim at your own pace with my self-study Core Vim Course.

Learn more

Learn Vim at your own pace with my self-study Core Vim Course.

Tidying whitespace

#4

Run time:

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.

Shownotes

Converting between tabs and spaces

The command for converting between tabs and spaces is:

:retab!

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:

:%s/\s\+$//e

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()

This example runs the autocommand on python and javascript files. Use this as a template, and add other filetypes to suit your needs.

Delete blank lines

You can delete all blank lines by running the following command:

:g/^$/d

Further reading

Updates

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 StripTrailingWhitespaces()

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 <leader>. The $ 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.

Comments

Level-up your Vim

Training

Boost your productivity with a Vim training class. Join a public class, or book a private session for your team.

Drew hosted a private Vim session for the shopify team that was one of the best workshops I have ever attended.

John Duff, Director of Engineering at Shopify

Publications

Make yourself a faster and more efficient developer with the help of these publications, including Practical Vim (Pragmatic Bookshelf 2012), which has over 50 five-star reviews on Amazon.

After reading it, I've switched to vim as my default editor on a daily basis with no regrets. ★★★★★

Javier Collado

Learn to use Vim efficiently in your Ruby projects

In association with thoughtbot, one of the most well respected Rails consultancies in the world, I've produced a series of screencasts on how to make navigating your Ruby projects with Vim ultra-efficient. Along the way, you’ll also learn how to make Ruby blocks a first-class text object in Vim. This lets you edit Ruby code at a higher level of abstraction. Available to buy from thoughtbot..