2

Say I have several files with different line endings (i.e. some have LF and others have CR+LF). If I somehow run diff on them and load the diff into Emacs (e.g. with C-x v D, or just dumping the diff to a file and visiting it), I get mixed line endings in the diff buffer. This is more than just annoying ^Ms at the end of some lines, it breaks diff-apply-hunk. If I delete the CRs, diff-apply-hunk works, but at the expense of editing the buffer, which is undesirable when editing patch files.

How do others deal with this? Is there a way to make the line endings in the diff buffer consistent without changing the buffer contents?

jpkotta
  • 498
  • 2
  • 11

1 Answers1

1

Here's what I have so far:

(defun diff-delete-trailing-CR ()
  "Delete trailing carriage returns (^M) in a `diff-mode' buffer."
  (when (and (derived-mode-p 'diff-mode)
           (buffer-file-name)
           (save-excursion
             (goto-char (point-min))
             (re-search-forward "\r$" nil t))
           (y-or-n-p "Strip trailing carriage returns? "))
    (let ((inhibit-read-only t))
      (save-excursion
        (goto-char (point-min))
        (while (re-search-forward "\r+$" nil t)
          (replace-match "" nil nil)))
      (set-buffer-modified-p nil))))

(add-hook 'diff-mode-hook #'diff-delete-trailing-CR)

It at least ignores non-file buffers and buffers that don't have any CRs.

jpkotta
  • 498
  • 2
  • 11