Whitespace cleanup
Good developers are very careful about the proper use of whitespace in their files - there should be no empty lines at the beginning of a file, no empty lines at the end of a file, no trailing whitespace, no mixture of tabs and spaces, etc.
Emacs, naturally, wants to help with every problem possible and
provides a very nice solution in the form of the whitespace-cleanup
command. It’s a much more powerful alternative to the older
delete-trailing-whitespace command, that simply deletes trailing
whitespace, and it’s aware of the whitespace-style variable, used by whitespace-mode.
It usually applies to the whole buffer, but in transient-mark-mode
when the mark is active, it applies to the region. It also
applies to the region when it is not in transient mark mode, the
mark is active and C-u was pressed just before
calling whitespace-cleanup interactively. There is also a similar
command called whitespace-cleanup-region.
The problems cleaned up are (borrowed from the official documentation):
-
Empty lines at beginning of buffer.
-
Empty lines at end of buffer. If
whitespace-styleincludes the valueempty, remove all empty lines at beginning and/or end of buffer. -
8 or more SPACEs at beginning of line. If
whitespace-styleincludes the valueindentation: replace 8 or more SPACEs at beginning of line by TABs, ifindent-tabs-modeis non-nil; otherwise, replace TABs by SPACEs. Ifwhitespace-styleincludes the valueindentation::tab, replace 8 or more SPACEs at beginning of line by TABs. Ifwhitespace-styleincludes the valueindentation::space, replace TABs by SPACEs. -
SPACEs before TAB. If
whitespace-styleincludes the valuespace-before-tab: replace SPACEs by TABs, ifindent-tabs-modeis non-nil; otherwise, replace TABs by SPACEs. Ifwhitespace-styleincludes the valuespace-before-tab::tab, replace SPACEs by TABs. Ifwhitespace-styleincludes the valuespace-before-tab::space, replace TABs by SPACEs. -
SPACEs or TABs at end of line. If
whitespace-styleincludes the valuetrailing, remove all SPACEs or TABs at end of line. -
8 or more SPACEs after TAB. If
whitespace-styleincludes the valuespace-after-tab: replace SPACEs by TABs, ifindent-tabs-modeis non-nil; otherwise, replace TABs by SPACEs. Ifwhitespace-styleincludes the valuespace-after-tab::tab, replace SPACEs by TABs. Ifwhitespace-styleincludes the valuespace-after-tab::space, replace TABs by SPACEs.
It might be a good idea to add whitespace-cleanup to your
before-save-hook so that every buffer would be cleaned up before it’s saved:
(add-hook 'before-save-hook 'whitespace-cleanup)
For programming languages that rely on tabs being tabs you should
enable indent-tabs-mode (as noted above). Here’s an example for
makefile-mode:
(add-hook 'makefile-mode-hook 'indent-tabs-mode)
Prelude adds
whitespace-cleanup to before-save-hook by default.