Smarter trailing whitespace deletion

I used to use delete-trailing-whitespace in my local-file-write-hooks for any source file I edited, but I had to disable it a while back. Many files containing legacy source were extremely messy in this regard, and it made making simple fixes harder to track, since there was a large amount of noise in the diff from the whitespace changes.

But I just solved this. Here at Digg, we document all new code with phpDocumentor. Leveraging this, I wrote a new function to examine the header of the source file and strip whitespace if I have an @author tag.

(defun maybe-delete-trailing-whitespace ()
  "Delete trailing whitespace if I am the author of this file."
  (interactive)
  (and (delete-trailing-whitespacep) (delete-trailing-whitespace)))

(defun delete-trailing-whitespacep ()
  "Should we delete trailing whitespace when saving this file?"
  (save-excursion
    (goto-char (point-min))
    (next-line 25)
    (let ((pos (point)))
      (goto-char (point-min))
      (re-search-forward (concat "@author +" user-full-name) pos t))))

(defun progmodes-write-hooks ()
  "Hooks which run on file write for programming modes"
  (prog1 nil
    (set-buffer-file-coding-system 'utf-8-unix)
    (untabify-buffer)
    (copyright-update)
    (maybe-delete-trailing-whitespace)))

(defun progmodes-hooks ()
  "Hooks for all programming modes"
  (add-hook 'local-write-file-hooks 'progmodes-write-hooks))

(add-hook 'php-mode-hook 'progmodes-hooks)
(add-hook 'js2-mode-hook 'progmodes-hooks)
;; Repeat for any other mode for editing source

It works a treat, happily stripping trailing whitespace if I’m listed as an author in the header, and leaving it unmolested otherwise. I’m not entirely satisfied with delete-trailing-whitespacep, which feels a little graceless. Maybe someone knows a better way to do it?

2008/08/15
Previously On Atomized:

Discussion

[...] Smarter trailing whitespace deletionSplitting up XML with XSLT [...]

Atomized » Blog Archive » A fix for my whitespace deletion
2008/09/11

I check in all whitespace changes in a separate commit.

Paul
2008/09/12

Or, you could tell diff to ignore whitespace.

Michael Campbell
2008/09/13

@Paul, Yeah, I try to keep those kinds of changes separate as well.

Ian
2008/09/13

@Michael The true problem is with Subvesrion. Gratuitous whitespace changes often lead to conflicts when merging changesets. So I just avoid messing with the whitespace in other coder’s source.

Ian
2008/09/13

I use the following alias to help me ignore whitespace changes with SVN diffs. However, you would have to add similar logic to any tools you might use to do diffs as well.

alias svnd=’svn diff –diff-cmd diff -x -uw’

Then just do: $ svnd

Kyle Sherman
2008/10/03

Participate