I was over at vimcasts and I stumbled upon the episode on Tidying whitespace.
They came up with a function that removes trailing whitespace. Unlike my “homemade” solution, it goes the extra mile by keeping the history clean and putting your cursor back to where it was before you invoked the command.
" 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
There’s room for improvement, however. Although the Single Responsibility Principle is used to talk about classes, arguably it also applies to functions. That function doesn’t do one thing, it does two (useful) things: saving the “state” and executing a command to remove the trailing whitespace.
Here’s a function that preserves the state:
" 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
Notice how you can inject the command into that function. Even if Vim does function pointers (to some extent), let’s just punt on this one and pass a string.
Here’s the mapping to strip out trailing whitespace:
Back on Tidying whitespace, k00pa mentioned in the comments how he modified the original function to perform the same indentation. But, it was a copy and paste(!). With the “Preserve” function, we can turn this into a one-liner.