Monday, May 23, 2011

Identify trailing whitepace characters at end of line and end of file in Emacs

One of my pet peeves is hidden whitespace characters at the end of a line or at the end of a file. These whitespace characters make navigation more cumbersome. For example, suppose you want to edit the rightmost word on a line. You press ctrl-e or the end key (to take you to the end of the line) and the cursor takes you to a location beyond the rightmost word. You discover there are whitespace characters between the rightmost word and the cursor. This is counter productive. You can force Emacs to emphasize the trailing whitespace characters by adding the following settings to your .emacs file. You will no longer be surprised by hidden whitespace characters again!
(setq-default show-trailing-whitespace t)
(setq default-indicate-empty-lines t)
Thanks Raimon Grau for the suggestion of automatically removing trailing whitespace during saving of a file.
 (add-hook 'before-save-hook 'delete-trailing-whitespace)


Raimon Grau said...

If you want to go one step further, you can tell emacs to delete whitespaces using M-x delete-trailing-whitespace , and even hook this function to before-save-hook.

I wrote a post about this same issue in my blog. I hope you enjoy it. :)


tsengf said...

Great suggestion!