(add-hook 'before-save-hook 'd-before-save-hook)

(defun d-before-save-hook ()
  "Trims excess spaces at ends of line"
  (when (not (eq major-mode 'hexl-mode))
    (read-only-mode -1)
    (goto-char (point-min))
    (when (and t
               ;;(not (save-excursion (re-search-forward (make-string 1 0) nil t))) ;; ^@
               ;;(not (save-excursion (re-search-forward (make-string 1 1) nil t))) ;; ^a
               ;;(not (save-excursion (re-search-forward (make-string 1 2) nil t))) ;; ^b
               ;;(not (save-excursion (re-search-forward (make-string 1 3) nil t))) ;; ^c
               ;;(not (save-excursion (re-search-forward (make-string 1 4) nil t))) ;; ^d
               ;;(not (save-excursion (re-search-forward (make-string 1 5) nil t))) ;; ^e
               ;;(not (save-excursion (re-search-forward (make-string 1 6) nil t))) ;; ^f
               ;;(not (save-excursion (re-search-forward (make-string 1 7) nil t))) ;; ^g
               ;;(not (save-excursion (re-search-forward (make-string 1 8) nil t))) ;; ^h
               ;; --------------------------------------------------------
               ;;(not (re-search-forward (make-string 1 9) nil t)) ;; ^i
               ;;(not (re-search-forward (make-string 1 10) nil t)) ;; ^j
               ;;(not (save-excursion (re-search-forward (make-string 1 11) nil t))) ;; ^k
               ;;(not (re-search-forward (make-string 1 12) nil t)) ;; ^l
               ;;(not (re-search-forward (make-string 1 13) nil t)) ;; ^m
               ;;-----------------------------------------------------
               ;;(not (save-excursion (re-search-forward (make-string 1 14) nil t))) ;; ^n
               ;;(not (save-excursion (re-search-forward (make-string 1 15) nil t))) ;; ^o
               ;;(not (save-excursion (re-search-forward (make-string 1 16) nil t))) ;; ^p
               ;;(not (save-excursion (re-search-forward (make-string 1 17) nil t))) ;; ^q
               ;;(not (save-excursion (re-search-forward (make-string 1 18) nil t))) ;; ^r
               ;;(not (save-excursion (re-search-forward (make-string 1 19) nil t))) ;; ^s
               ;;(not (save-excursion (re-search-forward (make-string 1 20) nil t))) ;; ^t
               ;;(not (save-excursion (re-search-forward (make-string 1 21) nil t))) ;; ^u
               ;;(not (save-excursion (re-search-forward (make-string 1 22) nil t))) ;; ^v
               ;;(not (save-excursion (re-search-forward (make-string 1 23) nil t))) ;; ^w
               ;;(not (save-excursion (re-search-forward (make-string 1 24) nil t))) ;; ^x
               ;;(not (save-excursion (re-search-forward (make-string 1 25) nil t))) ;; ^y
               ;;(not (save-excursion (re-search-forward (make-string 1 26) nil t))) ;; ^z
               )
      (goto-char (point-min))
      (while (re-search-forward "[^ ]\\([ \t]*$\\)" nil t)
        (delete-region (match-beginning 1) (match-end 1)))
      )))

(provide 'd-before-save-hook)
