Subject: 23.3; Rmail's rmail-output fails when destination mailbox is empty and visited [PATCH]
From: Mark Lillibridge <[email-masked]>
To: [email-masked]
Date: Sun, 06 Nov 2011 14:45:44 -0800
List-Id: <debbugs-submit.debbugs.gnu.org>

Reproducing:

    Visit a new Rmail file (e.g., using 'i') then output a message to
that new file from another ('o').  Return to that file's buffer and save
it ('s').  Notice the "invalid mbox file" error message...

    This bug is caused by the following code in the function
rmail-output-to-rmail-buffer: 
rmailout.el:379:
    ;; Make sure the last old message ends with a blank line.
    (goto-char (point-max))
    (rmail-ensure-blank-line)

This code is attempting to ensure that the current rmail-buffer is
in valid mbox format; in particular, that it ends with a blank line.
However, empty mbox files do *not* end with a blank line so this code
corrupts the mailbox when empty by adding an extra newline:

    (defun rmail-ensure-blank-line ()
      "Ensure a message ends in a blank line.
    Call with point at the end of the message."
      (unless (bolp)
        (insert "\n"))
      (unless (looking-back "\n\n")
        (insert "\n")))
    
The result is that the outputted message is preceded by a blank line,
which is not valid mbox format.  The fix is simple and similar to that
of bug number 9974:

    (goto-char (point-max))
    ;; Make sure current Rmail buffer is in valid mbox format (end
    ;; with a blank line unless no messages):
    ;;   (fixes damage caused by bug #9974)
    (unless (bobp)
      (while (not (looking-back "\n\n"))
	(insert "\n")))

A patch follows.

- Mark

ts-rhel5 [260]% ( setenv LC_ALL C ; setenv TZ UTC0 ; diff -Naur original-rmailout.el rmailout.el ) 
--- original-rmailout.el        2011-11-06 22:14:56.353674000 +0000
+++ rmailout.el 2011-11-06 22:23:30.723302000 +0000
@@ -376,9 +376,13 @@
     (rmail-maybe-set-message-counters)
     ;; Insert the new message after the last old message.
     (widen)
-    ;; Make sure the last old message ends with a blank line.
     (goto-char (point-max))
-    (rmail-ensure-blank-line)
+    ;; Make sure current Rmail buffer is in valid mbox format (end
+    ;; with a blank line unless no messages):
+    ;;   (fixes damage caused by bug #9974)
+    (unless (bobp)
+      (while (not (looking-back "\n\n"))
+       (insert "\n")))
     ;; Insert the new message at the end.
     (narrow-to-region (point-max) (point-max))
     (insert-buffer-substring tembuf)