Cùran's life
A Debian Developer's observations

14th July 2011 18:51 (GMT)
Vim: automatically delete whitespaces and CRs

Yesterday's blog entry garnered a lot of attention and some responses (in the form of e-mails, which is totally fine). Two of them deserve, as far as I'm concerend, their own little entry in the mini-series I kicked off. So, here we go:

First up was reader Sylvain "ythier" Hitier, who suggested adding

set list lcs=eol:¶,tab:»-,trail:·

to your .vimrc and making use of the :list option. The above line will highlight tabulators, trailing whitespaces and the end of a line. And it'll allow you to differentiate the three.
A warning though: you would want to deactivate this, in case you want to do copy and pasting with your mouse.

[UPDATE] Sylvain just sent me a little key binding for C&P he's using to toggle the highlighting:

function CutPaste()
  setlocal paste! nu! list!
endfunction
map <F10> :call CutPaste()

[/UPDATE]

The second really nice idea came by courtesy of Thilo Six to my attention:

" automatically delete trailing whitespace & Dos-returns    {{{2
fun! <SID>MyDeleteTrailingWhitespace()
  if ! &bin
    let l:l = line(".")
    let l:c = col(".")
    silent! :%s/[\r \t]\+$//
    call histdel("search", -1)
    call cursor(l:l, l:c)
  endif
endfun
autocmd BufWritePre,FileWritePre * call <SID>MyDeleteTrailingWhitespace()

The above snippet will automatically delete trailing whitespace and carriage returns as added by a lot of Windows programs.
Again a little warning: the function is executed automatically, so be sure you have only replacements included in the regular expression you really want to get deleted!

Thanks a lot for all the input I've received!

Permalink | cheat-sheet, debian, vim.

License: Creative Commons Attribution-ShareAlike 3.0 Unported License | Imprint (Impressum) | Compiled with Chronicle v4.6

Archives

Tags
Feed
Support my Debian work!
Validated