help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Comment request: a solution for smart trailing whitespace removal.


From: Óscar Fuentes
Subject: Comment request: a solution for smart trailing whitespace removal.
Date: Sun, 10 Feb 2008 07:47:28 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.0.60 (windows-nt)

For those of use plagued with source files containing lines with
trailing whitespaces, sometimes all we can do is to do not make things
worse, which means not adding more trailing whitespaces.

After some thought, I noticed that a common pattern is to do a diff
before committing the changes to the source control system. The first
idea was to detect new trailing whitespace at that point. This can be
achieved by

(defun my-diff-mode-hook ()
  (setq show-trailing-whitespace t))

(add-hook 'diff-mode-hook 'my-diff-mode-hook t)

This makes very easy to notice trailing whitespace introduced by the
changes we made to the source file.

The next step is to automatically remove trailing whitespace. Below is a
function for that.

I'll appreciate your ideas, corrections, fixes, enhancements, rants,
etc.

(defun delete-trailing-whitespace-from-diff ()
  "When on a buffer with diff-mode, inspects the differences and
removes trailing whitespace (spaces, tabs) from the modified lines.
Shows a message with the name of the buffers that where changed.
If a file referenced on the diff has no buffer and need to be fixed,
the file is loaded."
  (interactive)
  ;; TODO: Check that we are in diff-mode or one of its derived modes.
  (goto-char (point-min))
  ;; Skip header.
  ;; TODO: Support for other diff formats' header.
  (re-search-forward "^[+++ ]" (point-max) t)
  (setq modified-buffers nil)
  (while (re-search-forward "^[+!>].*[ \t]+$" (point-max) t)
    (save-excursion
      (destructuring-bind (buf line-offset pos src dst &optional switched)
          (diff-find-source-location) ;; other-file)
        (set-buffer buf)
        (save-excursion
          (goto-char (+ (car pos) (cdr src)))
          (let ((eol (progn (end-of-line) (point)))
                (bol (progn (beginning-of-line) (point))))
            (when (re-search-forward "\\(\\([ \t]\\)+\\)$" eol t)
              (delete-region (match-beginning 1) (match-end 1))
              (message (buffer-name buf))
              (setq modified-buffers (cons buf modified-buffers))))))))
  (if modified-buffers
      (let ((msg "This buffers were fixed:"))
        (dolist (f modified-buffers)
          (setq msg (concat msg " `" (buffer-name f) "'")))
        (message msg))
    (message "No fixes needed.")))

-- 
Oscar





reply via email to

[Prev in Thread] Current Thread [Next in Thread]