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

13th July 2011 07:53 (GMT)
Vim: How to prevent trailing whitespaces

As the local geek I get all sorts of (Linux) questions asked, like "How can you delete the nth line with Sed?" or "Is there a way to search for the following in a file?" (the latter being a request to construct a regular expression for grep). And while I'm pretty sure, you can find answers for such questions quickly with $SEARCH_ENGINE I find myself generally typing the answer into the IM session. This, and just seeing Bernd's post about Vim on Planet Debian, prompted me to start a little, irregular series of posts, to which I can point people, whenever I get asked such questions.

I start this off with a tip for Vim, a very powerful text editor. The problem is simple: you get (source code) files with trailing whitespaces (sometimes accumulated in "empty" lines). This makes diffing (and merging) difficult. Thus the question is: how do I prevent that from happening? How do I notice, that I have whitespaces at the end of a line? The solution consists of two lines in your .vimrc:

:highlight TrailWhitespace ctermbg=red guibg=red
:match TrailWhitespace /\s\+$\| \+\ze\t/

If you just want this functionality if syntax highlighting is also active, then you should use

:autocmd Syntax * syn match TrailWhitespace /\s\+$\| \+\ze\t/

instead of the :match line. The regular expression used in both cases matches trailing whitespaces and whitespaces in front of tabs.

Of course there are several other options on how to do this or what you might want to highlight, but that would be beyond the scope of this little post.

Permalink | cheat-sheet, debian, vim.

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


Support my Debian work!