* Files shouldn't be wrongfully deleted on occasion while trying to quit.
  Patch: save-buffer.diff
  Added-by: Jerome Marant <jerome@debian.org>
  Date: Sun, 26 Oct 2003 17:48:46 +0100
  Status: has been incorporated upstream

  Emacs should no longer wrongfully delete a file when the user
  changes the coding system of a buffer, then tries to save the
  buffer, then receives a warning that the buffer cannot be safely
  encoded, and then finally cancels the save and exits emacs without
  saving that buffer.

diff -urNad /home/jerome/pkg/emacs21/svn/emacs21/lisp/files.el emacs21/lisp/files.el
--- /home/jerome/pkg/emacs21/svn/emacs21/lisp/files.el	2003-10-01 20:01:28.000000000 +0200
+++ emacs21/lisp/files.el	2003-10-26 17:45:31.000000000 +0100
@@ -2207,7 +2207,8 @@
 			     (copy-file real-file-name backupname t t)))
 			;; rename-file should delete old backup.
 			(rename-file real-file-name backupname t)
-			(setq setmodes (file-modes backupname)))
+			(setq setmodes
+			      (cons (file-modes backupname) backupname)))
 		    (file-error
 		     ;; If trouble writing the backup, write it in ~.
 		     (setq backupname (expand-file-name
@@ -2682,7 +2683,7 @@
 		  (nthcdr 10 (file-attributes buffer-file-name)))
 	    (if setmodes
 		(condition-case ()
-		    (set-file-modes buffer-file-name setmodes)
+		    (set-file-modes buffer-file-name (car setmodes))
 		  (error nil))))
 	  ;; If the auto-save file was recent before this command,
 	  ;; delete it now.
@@ -2760,7 +2761,8 @@
 	    ;; Since we have created an entirely new file
 	    ;; and renamed it, make sure it gets the
 	    ;; right permission bits set.
-	    (setq setmodes (file-modes buffer-file-name))
+	    (setq setmodes (or setmodes (cons (file-modes buffer-file-name)
+					      buffer-file-name)))
 	    ;; We succeeded in writing the temp file,
 	    ;; so rename it.
 	    (rename-file tempname buffer-file-name t))
@@ -2770,10 +2772,18 @@
 	;; (setmodes is set) because that says we're superseding.
 	(cond ((and tempsetmodes (not setmodes))
 	       ;; Change the mode back, after writing.
-	       (setq setmodes (file-modes buffer-file-name))
-	       (set-file-modes buffer-file-name (logior setmodes 128))))
-	(write-region (point-min) (point-max)
-		      buffer-file-name nil t buffer-file-truename)))
+	       (setq setmodes (cons (file-modes buffer-file-name) buffer-file-name))
+	       (set-file-modes buffer-file-name (logior (car setmodes) 128))))
+	(let (success)
+	  (unwind-protect
+	      (progn
+		(write-region (point-min) (point-max)
+			      buffer-file-name nil t buffer-file-truename)
+		(setq success t))
+	    ;; If we get an error writing the new file, and we made
+	    ;; the backup by renaming, undo the backing-up.
+	    (and setmodes (not success)
+		 (rename-file (cdr setmodes) buffer-file-name))))))
     setmodes))
 
 (defun save-some-buffers (&optional arg pred)
