]> code.delx.au - gnu-emacs/blobdiff - lisp/mail/rmail.el
Update.
[gnu-emacs] / lisp / mail / rmail.el
index 6e3056da4074bef773adcaa5e2be44e9444ff53f..078a4518adf1071ea11d8debbf4b7a8f2223e28a 100644 (file)
@@ -1,7 +1,7 @@
 ;;; rmail.el --- main code of "RMAIL" mail reader for Emacs
 
 ;; Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995, 1996, 1997, 1998,
-;;   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
+;;   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
 ;;   Free Software Foundation, Inc.
 
 ;; Maintainer: FSF
 ;;
 
 (require 'mail-utils)
-(eval-when-compile (require 'mule-util)) ; for detect-coding-with-priority
+
+(defconst rmail-attribute-header "X-RMAIL-ATTRIBUTES"
+  "The header that stores the Rmail attribute data.")
+
+(defconst rmail-keyword-header "X-RMAIL-KEYWORDS"
+  "The header that stores the Rmail keyword data.")
+
+;;; Attribute indexes
+
+(defconst rmail-answered-attr-index 0
+  "The index for the `answered' attribute.")
+
+(defconst rmail-deleted-attr-index 1
+  "The index for the `deleted' attribute.")
+
+(defconst rmail-edited-attr-index 2
+  "The index for the `edited' attribute.")
+
+(defconst rmail-filed-attr-index 3
+  "The index for the `filed' attribute.")
+
+(defconst rmail-retried-attr-index 4
+  "The index for the `retried' attribute.")
+
+(defconst rmail-forwarded-attr-index 5
+  "The index for the `forwarded' attribute.")
+
+(defconst rmail-unseen-attr-index 6
+  "The index for the `unseen' attribute.")
+
+(defconst rmail-resent-attr-index 7
+  "The index for the `resent' attribute.")
+
+(defconst rmail-attr-array
+  '[(?A "answered")
+    (?D "deleted")
+    (?E "edited")
+    (?F "filed")
+    (?R "retried")
+    (?S "forwarded")
+    (?U "unseen")
+    (?r "resent")]
+  "An array that provides a mapping between an attribute index,
+its character representation and its display representation.")
 
 (defvar deleted-head)
 (defvar font-lock-fontified)
 (defvar mail-abbrev-syntax-table)
 (defvar mail-abbrevs)
 (defvar messages-head)
-(defvar rmail-use-spam-filter)
-(defvar rsf-beep)
-(defvar rsf-sleep-after-message)
 (defvar total-messages)
 (defvar tool-bar-map)
 
-; These variables now declared in paths.el.
-;(defvar rmail-spool-directory "/usr/spool/mail/"
-;  "This is the name of the directory used by the system mailer for\n\
-;delivering new mail.  Its name should end with a slash.")
-;(defvar rmail-file-name
-;  (expand-file-name "~/RMAIL")
-;  "")
+(defvar rmail-header-style 'normal
+  "The current header display style choice, one of
+'normal (selected headers) or 'full (all headers).")
+
+;; rmail-spool-directory and rmail-file-name are defined in paths.el.
 
 (defgroup rmail nil
   "Mail reader for Emacs."
   :prefix "rmail-edit-"
   :group 'rmail)
 
-(defgroup rmail-obsolete nil
-  "Rmail obsolete customization variables."
-  :group 'rmail)
-
 (defcustom rmail-movemail-program nil
   "If non-nil, the file name of the `movemail' program."
   :group 'rmail-retrieve
   :type '(choice (const nil) string))
 
-(defcustom rmail-pop-password nil
-  "*Password to use when reading mail from POP server.
-Please use `rmail-remote-password' instead."
-  :type '(choice (string :tag "Password")
-                (const :tag "Not Required" nil))
-  :group 'rmail-obsolete)
-
-(defcustom rmail-pop-password-required nil
-  "*Non-nil if a password is required when reading mail from a POP server.
-Please use rmail-remote-password-required instead."
-  :type 'boolean
-  :group 'rmail-obsolete)
+(define-obsolete-variable-alias 'rmail-pop-password
+  'rmail-remote-password "22.1")
 
 (defcustom rmail-remote-password nil
-  "*Password to use when reading mail from a remote server.
+  "Password to use when reading mail from a remote server.
 This setting is ignored for mailboxes whose URL already contains a password."
   :type '(choice (string :tag "Password")
                 (const :tag "Not Required" nil))
-  :set-after '(rmail-pop-password)
-  :set #'(lambda (symbol value)
-          (set-default symbol
-                       (if (and (not value)
-                                 (boundp 'rmail-pop-password)
-                                rmail-pop-password)
-                           rmail-pop-password
-                         value))
-          (setq rmail-pop-password nil))
   :group 'rmail-retrieve
   :version "22.1")
 
+(define-obsolete-variable-alias 'rmail-pop-password-required
+  'rmail-remote-password-required "22.1")
+
 (defcustom rmail-remote-password-required nil
-  "*Non-nil if a password is required when reading mail from a remote server."
+  "Non-nil if a password is required when reading mail from a remote server."
   :type 'boolean
-  :set-after '(rmail-pop-password-required)
-  :set #'(lambda (symbol value)
-          (set-default symbol
-                       (if (and (not value)
-                                 (boundp 'rmail-pop-password-required)
-                                rmail-pop-password-required)
-                           rmail-pop-password-required
-                         value))
-          (setq rmail-pop-password-required nil))
   :group 'rmail-retrieve
   :version "22.1")
 
 (defcustom rmail-movemail-flags nil
-  "*List of flags to pass to movemail.
+  "List of flags to pass to movemail.
 Most commonly used to specify `-g' to enable GSS-API authentication
 or `-k' to enable Kerberos authentication."
   :type '(repeat string)
@@ -173,17 +182,18 @@ please report it with \\[report-emacs-bug].")
 (defvar rmail-encoded-remote-password nil)
 
 (defcustom rmail-preserve-inbox nil
-  "*Non-nil means leave incoming mail in the user's inbox--don't delete it."
+  "Non-nil means leave incoming mail in the user's inbox--don't delete it."
   :type 'boolean
   :group 'rmail-retrieve)
 
 (defcustom rmail-movemail-search-path nil
-    "*List of directories to search for movemail (in addition to `exec-path')."
-    :group 'rmail-retrieve
-    :type '(repeat (directory)))
+  "List of directories to search for movemail (in addition to `exec-path')."
+  :group 'rmail-retrieve
+  :type '(repeat (directory)))
 
 (declare-function mail-position-on-field "sendmail" (field &optional soft))
 (declare-function mail-text-start "sendmail" ())
+(declare-function rmail-dont-reply-to "mail-utils" (destinations))
 (declare-function rmail-update-summary "rmailsum" (&rest ignore))
 
 (defun rmail-probe (prog)
@@ -257,20 +267,44 @@ Currently known variants are 'emacs and 'mailutils."
 (rmail-movemail-variant-p)
 
 ;;;###autoload
-(defcustom rmail-dont-reply-to-names nil "\
-*A regexp specifying addresses to prune from a reply message.
-A value of nil means exclude your own email address as an address
-plus whatever is specified by `rmail-default-dont-reply-to-names'."
+(defcustom rmail-user-mail-address-regexp nil
+  "Regexp matching user mail addresses.
+If non-nil, this variable is used to identify the correspondent
+when receiving new mail.  If it matches the address of the sender,
+the recipient is taken as correspondent of a mail.
+If nil \(default value\), your `user-login-name' and `user-mail-address'
+are used to exclude yourself as correspondent.
+
+Usually you don't have to set this variable, except if you collect mails
+sent by you under different user names.
+Then it should be a regexp matching your mail addresses.
+
+Setting this variable has an effect only before reading a mail."
+  :type '(choice (const :tag "None" nil) regexp)
+  :group 'rmail-retrieve
+  :version "21.1")
+
+;;;###autoload
+(defcustom rmail-dont-reply-to-names nil
+  "A regexp specifying addresses to prune from a reply message.
+If this is nil, it is set the first time you compose a reply, to
+a value which excludes your own email address, plus whatever is
+specified by `rmail-default-dont-reply-to-names'.
+
+Matching addresses are excluded from the CC field in replies, and
+also the To field, unless this would leave an empty To field."
   :type '(choice regexp (const :tag "Your Name" nil))
   :group 'rmail-reply)
 
 ;;;###autoload
-(defvar rmail-default-dont-reply-to-names "\\`info-" "\
-A regular expression specifying part of the default value of the
-variable `rmail-dont-reply-to-names', for when the user does not set
-`rmail-dont-reply-to-names' explicitly.  (The other part of the default
-value is the user's email address and name.)
-It is useful to set this variable in the site customization file.")
+(defvar rmail-default-dont-reply-to-names "\\`info-"
+  "Regexp specifying part of the default value of `rmail-dont-reply-to-names'.
+This is used when the user does not set `rmail-dont-reply-to-names'
+explicitly.  (The other part of the default value is the user's
+email address and name.)  It is useful to set this variable in
+the site customization file.  The default value is conventionally
+used for large mailing lists to broadcast announcements.")
+;; Is it really useful to set this site-wide?
 
 ;;;###autoload
 (defcustom rmail-ignored-headers
@@ -282,15 +316,16 @@ It is useful to set this variable in the site customization file.")
          "\\|^x-mailer:\\|^delivered-to:\\|^lines:"
          "\\|^content-transfer-encoding:\\|^x-coding-system:"
          "\\|^return-path:\\|^errors-to:\\|^return-receipt-to:"
-         "\\|^precedence:\\|^list-help:\\|^list-post:\\|^list-subscribe:"
+         "\\|^precedence:\\|^mime-version:"
+         "\\|^list-owner:\\|^list-help:\\|^list-post:\\|^list-subscribe:"
          "\\|^list-id:\\|^list-unsubscribe:\\|^list-archive:"
          "\\|^content-length:\\|^nntp-posting-date:\\|^user-agent"
          "\\|^importance:\\|^envelope-to:\\|^delivery-date\\|^openpgp:"
-         "\\|^mbox-line:\\|^cancel-lock:\\|^DomainKey-Signature:"
+         "\\|^mbox-line:\\|^cancel-lock:"
+         "\\|^DomainKey-Signature:\\|^dkim-signature:"
          "\\|^resent-face:\\|^resent-x.*:\\|^resent-organization:\\|^resent-openpgp:"
-
          "\\|^x-.*:")
-  "*Regexp to match header fields that Rmail should normally hide.
+  "Regexp to match header fields that Rmail should normally hide.
 \(See also `rmail-nonignored-headers', which overrides this regexp.)
 This variable is used for reformatting the message header,
 which normally happens once for each message,
@@ -302,7 +337,7 @@ go to that message and type \\[rmail-toggle-header] twice."
   :group 'rmail-headers)
 
 (defcustom rmail-nonignored-headers "^x-spam-status:"
-  "*Regexp to match X header fields that Rmail should show.
+  "Regexp to match X header fields that Rmail should show.
 This regexp overrides `rmail-ignored-headers'; if both this regexp
 and that one match a certain header field, Rmail shows the field.
 If this is nil, ignore all header fields in `rmail-ignored-headers'.
@@ -318,62 +353,65 @@ go to that message and type \\[rmail-toggle-header] twice."
 
 ;;;###autoload
 (defcustom rmail-displayed-headers nil
-  "*Regexp to match Header fields that Rmail should display.
+  "Regexp to match Header fields that Rmail should display.
 If nil, display all header fields except those matched by
 `rmail-ignored-headers'."
   :type '(choice regexp (const :tag "All"))
   :group 'rmail-headers)
 
 ;;;###autoload
-(defcustom rmail-retry-ignored-headers "^x-authentication-warning:" "\
-*Headers that should be stripped when retrying a failed message."
+(defcustom rmail-retry-ignored-headers "^x-authentication-warning:\\|^x-detected-operating-system:\\|^x-spam[-a-z]*:\\|content-type:\\|content-transfer-encoding:\\|mime-version:"
+  "Headers that should be stripped when retrying a failed message."
   :type '(choice regexp (const nil :tag "None"))
-  :group 'rmail-headers)
+  :group 'rmail-headers
+  :version "23.2")        ; added x-detected-operating-system, x-spam
 
 ;;;###autoload
-(defcustom rmail-highlighted-headers "^From:\\|^Subject:" "\
-*Regexp to match Header fields that Rmail should normally highlight.
-A value of nil means don't highlight."
+(defcustom rmail-highlighted-headers "^From:\\|^Subject:"
+  "Regexp to match Header fields that Rmail should normally highlight.
+A value of nil means don't highlight.  Uses the face `rmail-highlight'."
   :type 'regexp
   :group 'rmail-headers)
 
 (defface rmail-highlight
   '((t (:inherit highlight)))
-  "Face to use for highlighting the most important header fields."
+  "Face to use for highlighting the most important header fields.
+The variable `rmail-highlighted-headers' specifies which headers."
   :group 'rmail-headers
   :version "22.1")
 
 (defface rmail-header-name
   '((t (:inherit font-lock-function-name-face)))
-  "Face to use for highlighting the header names."
+  "Face to use for highlighting the header names.
+The variable `rmail-font-lock-keywords' specifies which headers
+get highlighted."
   :group 'rmail-headers
   :version "23.1")
 
-;;;###autoload
-(defcustom rmail-delete-after-output nil "\
-*Non-nil means automatically delete a message that is copied to a file."
+(defcustom rmail-delete-after-output nil
+  "Non-nil means automatically delete a message that is copied to a file."
   :type 'boolean
   :group 'rmail-files)
 
 ;;;###autoload
-(defcustom rmail-primary-inbox-list nil "\
-*List of files which are inboxes for user's primary mail file `~/RMAIL'.
-nil means the default, which is (\"/usr/spool/mail/$USER\")
-\(the name varies depending on the operating system,
-and the value of the environment variable MAIL overrides it)."
-  ;; Don't use backquote here, because we don't want to need it
-  ;; at load time.
+(defcustom rmail-primary-inbox-list nil
+  "List of files that are inboxes for your primary mail file `rmail-file-name'.
+If this is nil, uses the environment variable MAIL.  If that is
+unset, uses a file named by the function `user-login-name' in the
+directory `rmail-spool-directory' (whose value depends on the
+operating system).  For example, \"/var/mail/USER\"."
+  ;; Don't use backquote here, because we don't want to need it at load time.
+  ;; (That must be an old comment - it's dumped these days.)
   :type (list 'choice '(const :tag "Default" nil)
              (list 'repeat ':value (list (or (getenv "MAIL")
-                                             (concat "/var/spool/mail/"
-                                                     (getenv "USER"))))
+                                             (concat rmail-spool-directory
+                                                     (user-login-name))))
                    'file))
   :group 'rmail-retrieve
   :group 'rmail-files)
 
-;;;###autoload
 (defcustom rmail-mail-new-frame nil
-  "*Non-nil means Rmail makes a new frame for composing outgoing mail.
+  "Non-nil means Rmail makes a new frame for composing outgoing mail.
 This is handy if you want to preserve the window configuration of
 the frame where you have the RMAIL buffer displayed."
   :type 'boolean
@@ -381,29 +419,30 @@ the frame where you have the RMAIL buffer displayed."
 
 ;;;###autoload
 (defcustom rmail-secondary-file-directory "~/"
-  "*Directory for additional secondary Rmail files."
+  "Directory for additional secondary Rmail files."
   :type 'directory
   :group 'rmail-files)
 ;;;###autoload
 (defcustom rmail-secondary-file-regexp "\\.xmail$"
-  "*Regexp for which files are secondary Rmail files."
+  "Regexp for which files are secondary Rmail files."
   :type 'regexp
   :group 'rmail-files)
 
-;;;###autoload
 (defcustom rmail-confirm-expunge 'y-or-n-p
-  "*Whether and how to ask for confirmation before expunging deleted messages."
+  "Whether and how to ask for confirmation before expunging deleted messages.
+The value, if non-nil is a function to call with a question (string)
+as argument, to ask the user that question."
   :type '(choice (const :tag "No confirmation" nil)
                 (const :tag "Confirm with y-or-n-p" y-or-n-p)
                 (const :tag "Confirm with yes-or-no-p" yes-or-no-p))
   :version "21.1"
   :group 'rmail-files)
+(put 'rmail-confirm-expunge 'risky-local-variable t)
 
 ;;;###autoload
 (defvar rmail-mode-hook nil
   "List of functions to call when Rmail is invoked.")
 
-;;;###autoload
 (defvar rmail-get-new-mail-hook nil
   "List of functions to call when Rmail has retrieved new mail.")
 
@@ -414,11 +453,9 @@ the frame where you have the RMAIL buffer displayed."
   :options '(goto-address)
   :group 'rmail)
 
-;;;###autoload
 (defvar rmail-quit-hook nil
   "List of functions to call when quitting out of Rmail.")
 
-;;;###autoload
 (defvar rmail-delete-message-hook nil
   "List of functions to call when Rmail deletes a message.
 When the hooks are called, the message has been marked deleted but is
@@ -433,6 +470,13 @@ still the current message in the Rmail buffer.")
 (defvar rmail-mmdf-delim2 "^\001\001\001\001\n"
   "Regexp marking the end of an mmdf message.")
 
+;; FIXME Post-mbox, this is now unused.
+;; In Emacs-22, this was called:
+;;  i) the very first time a message was shown.
+;; ii) when toggling the headers to the normal state, every time.
+;; It's not clear what it should do now, since there is nothing that
+;; records when a message is shown for the first time (unseen is not
+;; necessarily the same thing).
 (defcustom rmail-message-filter nil
   "If non-nil, a filter function for new messages in RMAIL.
 Called with region narrowed to the message, including headers,
@@ -446,8 +490,8 @@ Each element of the list is of the form:
 
   (FOLDERNAME FIELD REGEXP [ FIELD REGEXP ] ... )
 
-Where FOLDERNAME is the name of a BABYL format folder to put the
-message.  If any of the field regexp's are nil, then it is ignored.
+Where FOLDERNAME is the name of a folder to put the message.
+If any of the field regexp's are nil, then it is ignored.
 
 If FOLDERNAME is \"/dev/null\", it is deleted.
 If FOLDERNAME is nil then it is deleted, and skipped.
@@ -461,7 +505,9 @@ FIELD/REGEXP pairs continue in the list.
 
 examples:
   (\"/dev/null\" \"from\" \"@spam.com\") ; delete all mail from spam.com
-  (\"RMS\" \"from\" \"rms@\") ; save all mail from RMS."
+  (\"RMS\" \"from\" \"rms@\") ; save all mail from RMS.
+
+Note that this is only applied in the folder specifed by `rmail-file-name'."
   :group 'rmail
   :version "21.1"
   :type '(repeat (sexp :tag "Directive")))
@@ -477,34 +523,47 @@ examples:
   "Regexp to delete from Subject line before inserting `rmail-reply-prefix'.")
 
 (defcustom rmail-display-summary nil
-  "*If non-nil, Rmail always displays the summary buffer."
+  "If non-nil, Rmail always displays the summary buffer."
   :group 'rmail-summary
   :type 'boolean)
 \f
 (defvar rmail-inbox-list nil)
 (put 'rmail-inbox-list 'permanent-local t)
 
-(defvar rmail-keywords nil)
-(put 'rmail-keywords 'permanent-local t)
-
 (defvar rmail-buffer nil
   "The RMAIL buffer related to the current buffer.
 In an RMAIL buffer, this holds the RMAIL buffer itself.
 In a summary buffer, this holds the RMAIL buffer it is a summary for.")
 (put 'rmail-buffer 'permanent-local t)
 
+(defvar rmail-was-converted nil
+  "Non-nil in an Rmail buffer that was just converted from Babyl format.")
+(put 'rmail-was-converted 'permanent-local t)
+
+(defvar rmail-seriously-modified nil
+  "Non-nil in an Rmail buffer that has been modified in a major way.")
+(put 'rmail-seriously-modified 'permanent-local t)
+
 ;; Message counters and markers.  Deleted flags.
 
-(defvar rmail-current-message nil)
+(defvar rmail-current-message nil
+  "Integer specifying the message currently being displayed in this folder.")
 (put 'rmail-current-message 'permanent-local t)
 
-(defvar rmail-total-messages nil)
+(defvar rmail-total-messages nil
+  "Integer specifying the total number of messages in this folder.
+Includes deleted messages.")
 (put 'rmail-total-messages 'permanent-local t)
 
-(defvar rmail-message-vector nil)
+(defvar rmail-message-vector nil
+  "Vector of markers specifying the start and end of each message.
+Element N and N+1 specify the start and end of message N.")
 (put 'rmail-message-vector 'permanent-local t)
 
-(defvar rmail-deleted-vector nil)
+(defvar rmail-deleted-vector nil
+  "A string of length `rmail-total-messages' plus one.
+Character N is either a space or \"D\", according to whether
+message N is deleted or not.")
 (put 'rmail-deleted-vector 'permanent-local t)
 
 (defvar rmail-msgref-vector nil
@@ -520,18 +579,27 @@ by substituting the new message number into the existing list.")
 
 (defvar rmail-summary-buffer nil)
 (put 'rmail-summary-buffer 'permanent-local t)
-(defvar rmail-summary-vector nil)
+(defvar rmail-summary-vector nil
+  "In an Rmail buffer, vector of (newline-terminated) strings.
+Element N specifies the summary line for message N+1.")
 (put 'rmail-summary-vector 'permanent-local t)
 
+;; Rmail buffer swapping variables.
+
+(defvar rmail-buffer-swapped nil
+  "If non-nil, `rmail-buffer' is swapped with `rmail-view-buffer'.")
+(make-variable-buffer-local 'rmail-buffer-swapped)
+(put 'rmail-buffer-swapped 'permanent-local t)
+
 (defvar rmail-view-buffer nil
   "Buffer which holds RMAIL message for MIME displaying.")
+(make-variable-buffer-local 'rmail-view-buffer)
 (put 'rmail-view-buffer 'permanent-local t)
 \f
 ;; `Sticky' default variables.
 
 ;; Last individual label specified to a or k.
 (defvar rmail-last-label nil)
-(put 'rmail-last-label 'permanent-local t)
 
 ;; Last set of values specified to C-M-n, C-M-p, C-M-s or C-M-l.
 (defvar rmail-last-multi-labels nil)
@@ -540,15 +608,11 @@ by substituting the new message number into the existing list.")
 (put 'rmail-last-regexp 'permanent-local t)
 
 (defcustom rmail-default-file "~/xmail"
-  "*Default file name for \\[rmail-output]."
-  :type 'file
-  :group 'rmail-files)
-(defcustom rmail-default-rmail-file "~/XMAIL"
-  "*Default file name for \\[rmail-output-to-rmail-file]."
+  "Default file name for \\[rmail-output]."
   :type 'file
   :group 'rmail-files)
 (defcustom rmail-default-body-file "~/mailout"
-  "*Default file name for \\[rmail-output-body-to-file]."
+  "Default file name for \\[rmail-output-body-to-file]."
   :type 'file
   :group 'rmail-files
   :version "20.3")
@@ -561,16 +625,14 @@ by substituting the new message number into the existing list.")
 
 This is set to nil by default.")
 
-;;;###autoload
 (defcustom rmail-enable-mime nil
-  "*If non-nil, RMAIL uses MIME feature.
+  "If non-nil, RMAIL uses MIME features.
 If the value is t, RMAIL automatically shows MIME decoded message.
 If the value is neither t nor nil, RMAIL does not show MIME decoded message
 until a user explicitly requires it.
 
-Even if the value is non-nil, you can't use MIME feature
-if the feature specified by `rmail-mime-feature' is not available
-in your session."
+Even if the value is non-nil, you can't use MIME features
+unless the feature specified by `rmail-mime-feature' is available."
   :type '(choice (const :tag "on" t)
                 (const :tag "off" nil)
                 (other :tag "when asked" ask))
@@ -579,7 +641,7 @@ in your session."
 (defvar rmail-enable-mime-composing nil
   "*If non-nil, RMAIL uses `rmail-insert-mime-forwarded-message-function' to forward.")
 
-;;;###autoload
+;; FIXME unused.
 (defvar rmail-show-mime-function nil
   "Function to show MIME decoded message of RMAIL file.
 This function is called when `rmail-enable-mime' is non-nil.
@@ -594,31 +656,30 @@ It is called with one argument FORWARD-BUFFER, which is a
 buffer containing the message to forward.  The current buffer
 is the outgoing mail buffer.")
 
-;;;###autoload
 (defvar rmail-insert-mime-resent-message-function nil
   "Function to insert a message in MIME format so it can be resent.
-This function is called if `rmail-enable-mime' is non-nil.
+This function is called by `rmail-resend' if `rmail-enable-mime' is non-nil.
 It is called with one argument FORWARD-BUFFER, which is a
 buffer containing the message to forward.  The current buffer
 is the outgoing mail buffer.")
 
-;;;###autoload
+;; FIXME one might want to pass a LIMIT, as per
+;; rmail-search-mime-header-function.
 (defvar rmail-search-mime-message-function nil
   "Function to check if a regexp matches a MIME message.
-This function is called if `rmail-enable-mime' is non-nil.
-It is called with two arguments MSG and REGEXP, where
+This function is called by `rmail-search-message' if
+`rmail-enable-mime' is non-nil.  It is called (with point at the
+start of the message) with two arguments MSG and REGEXP, where
 MSG is the message number, REGEXP is the regular expression.")
 
-;;;###autoload
 (defvar rmail-search-mime-header-function nil
   "Function to check if a regexp matches a header of MIME message.
-This function is called if `rmail-enable-mime' is non-nil.
-It is called with three arguments MSG, REGEXP, and LIMIT, where
-MSG is the message number,
-REGEXP is the regular expression,
-LIMIT is the position specifying the end of header.")
+This function is called by `rmail-message-regexp-p-1' if
+`rmail-enable-mime' is non-nil.  It is called (with point at the
+start of the header) with three arguments MSG, REGEXP, and LIMIT,
+where MSG is the message number, REGEXP is the regular
+expression, LIMIT is the position specifying the end of header.")
 
-;;;###autoload
 (defvar rmail-mime-feature 'rmail-mime
   "Feature to require to load MIME support in Rmail.
 When starting Rmail, if `rmail-enable-mime' is non-nil,
@@ -627,17 +688,16 @@ this feature is required with `require'.
 The default value is `rmail-mime'.  This feature is provided by
 the rmail-mime package available at <http://www.m17n.org/rmail-mime/>.")
 
-;;;###autoload
+;; FIXME this is unused.
 (defvar rmail-decode-mime-charset t
   "*Non-nil means a message is decoded by MIME's charset specification.
 If this variable is nil, or the message has not MIME specification,
 the message is decoded as normal way.
 
-If the variable `rmail-enable-mime' is non-nil, this variables is
+If the variable `rmail-enable-mime' is non-nil, this variable is
 ignored, and all the decoding work is done by a feature specified by
 the variable `rmail-mime-feature'.")
 
-;;;###autoload
 (defvar rmail-mime-charset-pattern
   (concat "^content-type:[ \t]*text/plain;"
          "\\(?:[ \t\n]*\\(?:format\\|delsp\\)=\"?[-a-z0-9]+\"?;\\)*"
@@ -646,10 +706,6 @@ the variable `rmail-mime-feature'.")
 The first parenthesized expression should match the MIME-charset name.")
 
 \f
-;;; Regexp matching the delimiter of messages in UNIX mail format
-;;; (UNIX From lines), minus the initial ^.  Note that if you change
-;;; this expression, you must change the code in rmail-nuke-pinhead-header
-;;; that knows the exact ordering of the \\( \\) subexpressions.
 (defvar rmail-unix-mail-delimiter
   (let ((time-zone-regexp
         (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
@@ -700,8 +756,14 @@ The first parenthesized expression should match the MIME-charset name.")
      "\\(remote from .*\\)?"
 
      "\n"))
-  nil)
-
+  "Regexp matching the delimiter of messages in UNIX mail format
+\(UNIX From lines), minus the initial ^.  Note that if you change
+this expression, you must change the code in `rmail-nuke-pinhead-header'
+that knows the exact ordering of the \\( \\) subexpressions.")
+
+;; FIXME the rmail-header-name headers ought to be customizable.
+;; It seems a bit arbitrary, for example, that all of the Date: line
+;; gets highlighted.
 (defvar rmail-font-lock-keywords
   ;; These are all matched case-insensitively.
   (eval-when-compile
@@ -710,7 +772,8 @@ The first parenthesized expression should match the MIME-charset name.")
           (cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
       (list '("^\\(From\\|Sender\\|Resent-From\\):"
              . 'rmail-header-name)
-           '("^Reply-To:.*$" . 'rmail-header-name)
+           '("^\\(Mail-\\)?Reply-To:.*$" . 'rmail-header-name)
+           ;; FIXME Mail-Followup-To should probably be here too.
            '("^Subject:" . 'rmail-header-name)
            '("^X-Spam-Status:" . 'rmail-header-name)
            '("^\\(To\\|Apparently-To\\|Cc\\|Newsgroups\\):"
@@ -745,20 +808,13 @@ The first parenthesized expression should match the MIME-charset name.")
                   (let ((rmail-total-messages total))
                     ,@body))
               (select-window window))))
-       (save-excursion
-        (set-buffer rmail-summary-buffer)
+       (with-current-buffer rmail-summary-buffer
         (let ((rmail-total-messages total))
           ,@body)))
      (rmail-maybe-display-summary)))
 \f
 ;;;; *** Rmail Mode ***
 
-;; This variable is dynamically bound.  The defvar is here to placate
-;; the byte compiler.
-
-(defvar rmail-enable-multibyte nil)
-
-
 (defun rmail-require-mime-maybe ()
   "Require `rmail-mime-feature' if that is non-nil.
 Signal an error and set `rmail-mime-feature' to nil if the feature
@@ -768,21 +824,22 @@ isn't provided."
        (require rmail-mime-feature)
       (error
        (display-warning
-       :warning
+       'rmail
        (format "Although MIME support is requested
 by setting `rmail-enable-mime' to non-nil, the required feature
 `%s' (the value of `rmail-mime-feature')
 is not available in the current session.
-So, the MIME support is turned off for the moment." 
-               rmail-mime-feature))
+So, the MIME support is turned off for the moment."
+               rmail-mime-feature)
+       :warning)
        (setq rmail-enable-mime nil)))))
 
 
 ;;;###autoload
 (defun rmail (&optional file-name-arg)
   "Read and edit incoming mail.
-Moves messages into file named by `rmail-file-name' (a babyl format file)
- and edits that file in RMAIL Mode.
+Moves messages into file named by `rmail-file-name' and edits that
+file in RMAIL Mode.
 Type \\[describe-mode] once editing that file, for a list of RMAIL commands.
 
 May be called with file name as argument; then performs rmail editing on
@@ -798,384 +855,337 @@ If `rmail-display-summary' is non-nil, make a summary for this RMAIL file."
         ;; Use find-buffer-visiting, not get-file-buffer, for those users
         ;; who have find-file-visit-truename set to t.
         (existed (find-buffer-visiting file-name))
-        ;; This binding is necessary because we must decide if we
-        ;; need code conversion while the buffer is unibyte
-        ;; (i.e. enable-multibyte-characters is nil).
-         (rmail-enable-multibyte
-          (if existed
-             (with-current-buffer existed enable-multibyte-characters)
-            (default-value 'enable-multibyte-characters)))
-        ;; Since the file may contain messages of different encodings
-        ;; at the tail (non-BYBYL part), we can't decode them at once
-        ;; on reading.  So, at first, we read the file without text
-        ;; code conversion, then decode the messages one by one by
-        ;; rmail-decode-babyl-format or
-        ;; rmail-convert-to-babyl-format.
-        (coding-system-for-read (and rmail-enable-multibyte 'raw-text))
-        run-mail-hook msg-shown)
-    ;; Like find-file, but in the case where a buffer existed
-    ;; and the file was reverted, recompute the message-data.
-    ;; We used to bind enable-local-variables to nil here,
-    ;; but that should not be needed now that rmail-mode
-    ;; sets it locally to nil.
-    ;; (Binding a variable locally with let is not safe if it has
-    ;; buffer-local bindings.)
+        run-mail-hook mail-buf msg-shown)
+    ;; Determine if an existing mail file has been changed behind the
+    ;; scene...
     (if (and existed (not (verify-visited-file-modtime existed)))
+       ;; The mail file has been changed.  Revisit it and reset the
+       ;; message state variables when in rmail mode.
        (progn
          (find-file file-name)
-         (if (and (verify-visited-file-modtime existed)
-                  (eq major-mode 'rmail-mode))
-             (progn (rmail-forget-messages)
-                    (rmail-set-message-counters))))
+         (when (and (verify-visited-file-modtime existed)
+                    (eq major-mode 'rmail-mode))
+           (rmail-swap-buffers-maybe)
+           (rmail-set-message-counters)))
+      ;; The mail file is either unchanged or not visited.  Visit it.
       (switch-to-buffer
-       (let ((enable-local-variables nil))
+       (let ((enable-local-variables nil)
+            ;; Force no-conversion by default, since that's what
+            ;; pre-mbox Rmail did with BABYL files (via
+            ;; auto-coding-regexp-alist).
+            (coding-system-for-read
+             (or coding-system-for-read 'no-conversion)))
         (find-file-noselect file-name))))
+    ;; Ensure that the collection and view buffers are in sync and
+    ;; ensure that a message is not being edited.
+    (if (eq major-mode 'rmail-mode)
+       (rmail-swap-buffers-maybe))
     (if (eq major-mode 'rmail-edit-mode)
        (error "Exit Rmail Edit mode before getting new mail"))
-    (if (and existed (> (buffer-size) 0))
-       ;; Buffer not new and not empty; ensure in proper mode, but that's all.
-       (or (eq major-mode 'rmail-mode)
-           (progn (rmail-mode-2)
-                  (setq run-mail-hook t)))
-      (setq run-mail-hook t)
-      (rmail-mode-2)
-      ;; Convert all or part to Babyl file if possible.
-      (rmail-convert-file)
-      (goto-char (point-max)))
-    ;; As we have read a file by raw-text, the buffer is set to
-    ;; unibyte.  We must make it multibyte if necessary.
-    (if (and rmail-enable-multibyte
-            (not enable-multibyte-characters))
-       (set-buffer-multibyte t))
-    ;; If necessary, scan to find all the messages.
+    (or (and existed (> (buffer-size) 0))
+       (setq run-mail-hook t))
+    ;; Ensure that the Rmail file is in mbox format, the buffer is in
+    ;; Rmail mode and has been scanned to find all the messages
+    ;; (setting the global message variables in the process).
+    (rmail-convert-file-maybe)
+    (unless (eq major-mode 'rmail-mode)
+      (rmail-mode-2))
+    (goto-char (point-max))
     (rmail-maybe-set-message-counters)
+    (setq mail-buf rmail-buffer)
+    ;; Show the first unread message and process summary mode.
     (unwind-protect
-       (unless (and (not file-name-arg)
-                    (rmail-get-new-mail))
-         (rmail-show-message (rmail-first-unseen-message)))
+       ;; Only get new mail when there is not a file name argument.
+       (unless file-name-arg
+         (setq msg-shown (rmail-get-new-mail)))
       (progn
+       (set-buffer mail-buf)
+       (or msg-shown
+           (rmail-show-message (rmail-first-unseen-message)))
        (if rmail-display-summary (rmail-summary))
        (rmail-construct-io-menu)
        (if run-mail-hook
            (run-hooks 'rmail-mode-hook))))))
 
-;; Given the value of MAILPATH, return a list of inbox file names.
-;; This is turned off because it is not clear that the user wants
-;; all these inboxes to feed into the primary rmail file.
-; (defun rmail-convert-mailpath (string)
-;   (let (idx list)
-;     (while (setq idx (string-match "[%:]" string))
-;       (let ((this (substring string 0 idx)))
-;      (setq string (substring string (1+ idx)))
-;      (setq list (cons (if (string-match "%" this)
-;                           (substring this 0 (string-match "%" this))
-;                         this)
-;                       list))))
-;     list))
-
-; I have checked that adding "-*- rmail -*-" to the BABYL OPTIONS line
-; will not cause emacs 18.55 problems.
-
-;; This calls rmail-decode-babyl-format if the file is already Babyl.
-
-(defun rmail-convert-file ()
-  (let (convert)
-    (widen)
-    (goto-char (point-min))
-    ;; If file doesn't start like a Babyl file,
-    ;; convert it to one, by adding a header and converting each message.
-    (cond ((looking-at "BABYL OPTIONS:"))
+(defun rmail-convert-file-maybe ()
+  "Determine if the file needs to be converted to mbox format."
+  (widen)
+  (goto-char (point-min))
+  ;; Detect previous Babyl format files.
+  (let ((case-fold-search nil))
+    (cond ((looking-at "BABYL OPTIONS:")
+          ;; The file is Babyl version 5.  Use unrmail to convert
+          ;; it.
+          (rmail-convert-babyl-to-mbox))
          ((looking-at "Version: 5\n")
-          ;; Losing babyl file made by old version of Rmail.
-          ;; Just fix the babyl file header; don't make a new one,
-          ;; so we don't lose the Labels: file attribute, etc.
+          ;; Losing babyl file made by old version of Rmail.  Fix the
+          ;; babyl file header and use unrmail to convert to mbox
+          ;; format.
           (let ((buffer-read-only nil))
-            (insert "BABYL OPTIONS: -*- rmail -*-\n")))
+            (insert "BABYL OPTIONS: -*- rmail -*-\n")
+            (rmail-convert-babyl-to-mbox)))
          ((equal (point-min) (point-max))
-          ;; Empty RMAIL file.  Just insert the header.
-          (rmail-insert-rmail-file-header))
-         (t
-          ;; Non-empty file in non-RMAIL format.  Add header and convert.
-          (setq convert t)
-          (rmail-insert-rmail-file-header)))
-    ;; If file was not a Babyl file or if there are
-    ;; Unix format messages added at the end,
-    ;; convert file as necessary.
-    (if (or convert
-           (save-excursion
-             (goto-char (point-max))
-             (search-backward "\n\^_")
-             (forward-char 2)
-             (looking-at "\n*From ")))
-       (let ((buffer-read-only nil))
-         (message "Converting to Babyl format...")
-         ;; If file needs conversion, convert it all,
-         ;; except for the BABYL header.
-         ;; (rmail-convert-to-babyl-format would delete the header.)
-         (goto-char (point-min))
-         (search-forward "\n\^_" nil t)
-         (narrow-to-region (point) (point-max))
-         (rmail-convert-to-babyl-format)
-         (message "Converting to Babyl format...done"))
-      (if (and (not rmail-enable-mime)
-              rmail-enable-multibyte)
-         ;; We still have to decode BABYL part.
-         (rmail-decode-babyl-format)))))
-
-(defun rmail-insert-rmail-file-header ()
-  (let ((buffer-read-only nil))
-    ;; -*-rmail-*- is here so that visiting the file normally
-    ;; recognizes it as an Rmail file.
-    (insert "BABYL OPTIONS: -*- rmail -*-
-Version: 5
-Labels:
-Note:   This is the header of an rmail file.
-Note:   If you are seeing it in rmail,
-Note:    it means the file has no messages in it.\n\^_")))
-
-;; Decode Babyl formatted part at the head of current buffer by
-;; rmail-file-coding-system, or if it is nil, do auto conversion.
-
-(defun rmail-decode-babyl-format ()
-  (let ((modifiedp (buffer-modified-p))
-       (buffer-read-only nil)
-       (coding-system rmail-file-coding-system)
-       from to)
+          (message "Empty Rmail file."))
+         ((looking-at "From "))
+         (t (error "Invalid mbox file")))))
+
+(defun rmail-error-bad-format (&optional msgnum)
+  "Report that the buffer is not in the mbox file format.
+MSGNUM, if present, indicates the malformed message."
+  (if msgnum
+      (error "Message %d is not a valid RFC2822 message" msgnum)
+    (error "Message is not a valid RFC2822 message")))
+
+(defun rmail-convert-babyl-to-mbox ()
+  "Convert the mail file from Babyl version 5 to mbox.
+This function also reinitializes local variables used by Rmail."
+  (let ((old-file (make-temp-file "rmail"))
+       (new-file (make-temp-file "rmail")))
+    (unwind-protect
+       (progn
+         (kill-all-local-variables)
+         (write-region (point-min) (point-max) old-file)
+         (unrmail old-file new-file)
+         (message "Replacing BABYL format with mbox format...")
+         (let ((inhibit-read-only t)
+               (coding-system-for-read 'raw-text)
+               (buffer-undo-list t))
+           (erase-buffer)
+           (insert-file-contents new-file)
+           ;; Rmail buffers need to be saved with Unix EOLs, or else
+           ;; the format will not be recognized.
+           (set-buffer-file-coding-system 'raw-text-unix)
+           (rmail-mode-1)
+           (rmail-perm-variables)
+           (rmail-variables)
+           (setq rmail-was-converted t)
+           (rmail-dont-modify-format)
+           (goto-char (point-max))
+           (rmail-set-message-counters))
+         (message "Replacing BABYL format with mbox format...done"))
+      (delete-file old-file)
+      (delete-file new-file))))
+
+(defun rmail-get-coding-system ()
+  "Return a suitable coding system to use for the current mail message.
+The buffer is expected to be narrowed to just the header of the message."
+  (save-excursion
     (goto-char (point-min))
-    (search-forward "\n\^_" nil t)     ; Skip BABYL header.
-    (setq from (point))
-    (goto-char (point-max))
-    (search-backward "\n\^_" from 'mv)
-    (setq to (point))
-    (unless (and coding-system
-                (coding-system-p coding-system))
-      (setq coding-system
-           ;; If rmail-file-coding-system is nil, Emacs 21 writes
-           ;; RMAIL files in emacs-mule, Emacs 22 in utf-8, but
-           ;; earlier versions did that with the current buffer's
-           ;; encoding.  So we want to favor detection of emacs-mule
-           ;; (whose normal priority is quite low) and utf-8, but
-           ;; still allow detection of other encodings if they won't
-           ;; fit.  The call to with-coding-priority below achieves
-           ;; that.
-           (with-coding-priority '(emacs-mule utf-8)
-             (detect-coding-region from to 'highest))))
-    (unless (eq (coding-system-type coding-system) 'undecided)
-      (set-buffer-modified-p t)                ; avoid locking when decoding
-      (let ((buffer-undo-list t))
-       (decode-coding-region from to coding-system))
-      (setq coding-system last-coding-system-used))
-    (set-buffer-modified-p modifiedp)
-    (setq buffer-file-coding-system nil)
-    (setq save-buffer-coding-system
-         (or coding-system 'undecided))))
-
-(defvar rmail-mode-map nil)
-(if rmail-mode-map
-    nil
-  (setq rmail-mode-map (make-keymap))
-  (suppress-keymap rmail-mode-map)
-  (define-key rmail-mode-map "a"      'rmail-add-label)
-  (define-key rmail-mode-map "b"      'rmail-bury)
-  (define-key rmail-mode-map "c"      'rmail-continue)
-  (define-key rmail-mode-map "d"      'rmail-delete-forward)
-  (define-key rmail-mode-map "\C-d"   'rmail-delete-backward)
-  (define-key rmail-mode-map "e"      'rmail-edit-current-message)
-  (define-key rmail-mode-map "f"      'rmail-forward)
-  (define-key rmail-mode-map "g"      'rmail-get-new-mail)
-  (define-key rmail-mode-map "h"      'rmail-summary)
-  (define-key rmail-mode-map "i"      'rmail-input)
-  (define-key rmail-mode-map "j"      'rmail-show-message)
-  (define-key rmail-mode-map "k"      'rmail-kill-label)
-  (define-key rmail-mode-map "l"      'rmail-summary-by-labels)
-  (define-key rmail-mode-map "\e\C-h" 'rmail-summary)
-  (define-key rmail-mode-map "\e\C-l" 'rmail-summary-by-labels)
-  (define-key rmail-mode-map "\e\C-r" 'rmail-summary-by-recipients)
-  (define-key rmail-mode-map "\e\C-s" 'rmail-summary-by-regexp)
-  (define-key rmail-mode-map "\e\C-t" 'rmail-summary-by-topic)
-  (define-key rmail-mode-map "m"      'rmail-mail)
-  (define-key rmail-mode-map "\em"    'rmail-retry-failure)
-  (define-key rmail-mode-map "n"      'rmail-next-undeleted-message)
-  (define-key rmail-mode-map "\en"    'rmail-next-message)
-  (define-key rmail-mode-map "\e\C-n" 'rmail-next-labeled-message)
-  (define-key rmail-mode-map "o"      'rmail-output-to-rmail-file)
-  (define-key rmail-mode-map "\C-o"   'rmail-output)
-  (define-key rmail-mode-map "p"      'rmail-previous-undeleted-message)
-  (define-key rmail-mode-map "\ep"    'rmail-previous-message)
-  (define-key rmail-mode-map "\e\C-p" 'rmail-previous-labeled-message)
-  (define-key rmail-mode-map "q"      'rmail-quit)
-  (define-key rmail-mode-map "r"      'rmail-reply)
-;; I find I can't live without the default M-r command -- rms.
-;;  (define-key rmail-mode-map "\er"  'rmail-search-backwards)
-  (define-key rmail-mode-map "s"      'rmail-expunge-and-save)
-  (define-key rmail-mode-map "\es"    'rmail-search)
-  (define-key rmail-mode-map "t"      'rmail-toggle-header)
-  (define-key rmail-mode-map "u"      'rmail-undelete-previous-message)
-  (define-key rmail-mode-map "w"      'rmail-output-body-to-file)
-  (define-key rmail-mode-map "x"      'rmail-expunge)
-  (define-key rmail-mode-map "."      'rmail-beginning-of-message)
-  (define-key rmail-mode-map "/"      'rmail-end-of-message)
-  (define-key rmail-mode-map "<"      'rmail-first-message)
-  (define-key rmail-mode-map ">"      'rmail-last-message)
-  (define-key rmail-mode-map " "      'scroll-up)
-  (define-key rmail-mode-map "\177"   'scroll-down)
-  (define-key rmail-mode-map "?"      'describe-mode)
-  (define-key rmail-mode-map "\C-c\C-s\C-d" 'rmail-sort-by-date)
-  (define-key rmail-mode-map "\C-c\C-s\C-s" 'rmail-sort-by-subject)
-  (define-key rmail-mode-map "\C-c\C-s\C-a" 'rmail-sort-by-author)
-  (define-key rmail-mode-map "\C-c\C-s\C-r" 'rmail-sort-by-recipient)
-  (define-key rmail-mode-map "\C-c\C-s\C-c" 'rmail-sort-by-correspondent)
-  (define-key rmail-mode-map "\C-c\C-s\C-l" 'rmail-sort-by-lines)
-  (define-key rmail-mode-map "\C-c\C-s\C-k" 'rmail-sort-by-labels)
-  (define-key rmail-mode-map "\C-c\C-n" 'rmail-next-same-subject)
-  (define-key rmail-mode-map "\C-c\C-p" 'rmail-previous-same-subject)
-  )
+    (if (re-search-forward rmail-mime-charset-pattern nil t)
+       (coding-system-from-name (match-string 1))
+      'undecided)))
+\f
+;;; Set up Rmail mode keymaps
+
+(defvar rmail-mode-map
+  (let ((map (make-keymap)))
+    (suppress-keymap map)
+    (define-key map "a"      'rmail-add-label)
+    (define-key map "b"      'rmail-bury)
+    (define-key map "c"      'rmail-continue)
+    (define-key map "d"      'rmail-delete-forward)
+    (define-key map "\C-d"   'rmail-delete-backward)
+    (define-key map "e"      'rmail-edit-current-message)
+    ;; If you change this, change the rmail-resend menu-item's :keys.
+    (define-key map "f"      'rmail-forward)
+    (define-key map "g"      'rmail-get-new-mail)
+    (define-key map "h"      'rmail-summary)
+    (define-key map "i"      'rmail-input)
+    (define-key map "j"      'rmail-show-message)
+    (define-key map "k"      'rmail-kill-label)
+    (define-key map "l"      'rmail-summary-by-labels)
+    (define-key map "\e\C-h" 'rmail-summary)
+    (define-key map "\e\C-l" 'rmail-summary-by-labels)
+    (define-key map "\e\C-r" 'rmail-summary-by-recipients)
+    (define-key map "\e\C-s" 'rmail-summary-by-regexp)
+    (define-key map "\e\C-t" 'rmail-summary-by-topic)
+    (define-key map "m"      'rmail-mail)
+    (define-key map "\em"    'rmail-retry-failure)
+    (define-key map "n"      'rmail-next-undeleted-message)
+    (define-key map "\en"    'rmail-next-message)
+    (define-key map "\e\C-n" 'rmail-next-labeled-message)
+    (define-key map "o"      'rmail-output)
+    (define-key map "\C-o"   'rmail-output-as-seen)
+    (define-key map "p"      'rmail-previous-undeleted-message)
+    (define-key map "\ep"    'rmail-previous-message)
+    (define-key map "\e\C-p" 'rmail-previous-labeled-message)
+    (define-key map "q"      'rmail-quit)
+    (define-key map "r"      'rmail-reply)
+    ;; I find I can't live without the default M-r command -- rms.
+    ;;  (define-key rmail-mode-map "\er"  'rmail-search-backwards)
+    (define-key map "s"      'rmail-expunge-and-save)
+    (define-key map "\es"    'rmail-search)
+    (define-key map "t"      'rmail-toggle-header)
+    (define-key map "u"      'rmail-undelete-previous-message)
+    (define-key map "v"      'rmail-mime)
+    (define-key map "w"      'rmail-output-body-to-file)
+    (define-key map "\C-c\C-w"    'rmail-widen)
+    (define-key map "x"      'rmail-expunge)
+    (define-key map "."      'rmail-beginning-of-message)
+    (define-key map "/"      'rmail-end-of-message)
+    (define-key map "<"      'rmail-first-message)
+    (define-key map ">"      'rmail-last-message)
+    (define-key map " "      'scroll-up)
+    (define-key map "\177"   'scroll-down)
+    (define-key map "?"      'describe-mode)
+    (define-key map "\C-c\C-s\C-d" 'rmail-sort-by-date)
+    (define-key map "\C-c\C-s\C-s" 'rmail-sort-by-subject)
+    (define-key map "\C-c\C-s\C-a" 'rmail-sort-by-author)
+    (define-key map "\C-c\C-s\C-r" 'rmail-sort-by-recipient)
+    (define-key map "\C-c\C-s\C-c" 'rmail-sort-by-correspondent)
+    (define-key map "\C-c\C-s\C-l" 'rmail-sort-by-lines)
+    (define-key map "\C-c\C-s\C-k" 'rmail-sort-by-labels)
+    (define-key map "\C-c\C-n" 'rmail-next-same-subject)
+    (define-key map "\C-c\C-p" 'rmail-previous-same-subject)
+
 \f
-(define-key rmail-mode-map [menu-bar] (make-sparse-keymap))
+    (define-key map [menu-bar] (make-sparse-keymap))
 
-(define-key rmail-mode-map [menu-bar classify]
-  (cons "Classify" (make-sparse-keymap "Classify")))
+    (define-key map [menu-bar classify]
+      (cons "Classify" (make-sparse-keymap "Classify")))
 
-(define-key rmail-mode-map [menu-bar classify input-menu]
-  nil)
+    (define-key map [menu-bar classify input-menu]
+      nil)
 
-(define-key rmail-mode-map [menu-bar classify output-menu]
-  nil)
+    (define-key map [menu-bar classify output-menu]
+      nil)
 
-(define-key rmail-mode-map [menu-bar classify output-body]
-  '("Output body to file..." . rmail-output-body-to-file))
+    (define-key map [menu-bar classify output-body]
+      '("Output body to file..." . rmail-output-body-to-file))
 
-(define-key rmail-mode-map [menu-bar classify output-inbox]
-  '("Output (inbox)..." . rmail-output))
+    (define-key map [menu-bar classify output-inbox]
+      '("Output..." . rmail-output))
 
-(define-key rmail-mode-map [menu-bar classify output]
-  '("Output (Rmail)..." . rmail-output-to-rmail-file))
+    (define-key map [menu-bar classify output]
+      '("Output as seen..." . rmail-output-as-seen))
 
-(define-key rmail-mode-map [menu-bar classify kill-label]
-  '("Kill Label..." . rmail-kill-label))
+    (define-key map [menu-bar classify kill-label]
+      '("Kill Label..." . rmail-kill-label))
 
-(define-key rmail-mode-map [menu-bar classify add-label]
-  '("Add Label..." . rmail-add-label))
+    (define-key map [menu-bar classify add-label]
+      '("Add Label..." . rmail-add-label))
 
-(define-key rmail-mode-map [menu-bar summary]
-  (cons "Summary" (make-sparse-keymap "Summary")))
+    (define-key map [menu-bar summary]
+      (cons "Summary" (make-sparse-keymap "Summary")))
 
-(define-key rmail-mode-map [menu-bar summary senders]
-  '("By Senders..." . rmail-summary-by-senders))
+    (define-key map [menu-bar summary senders]
+      '("By Senders..." . rmail-summary-by-senders))
 
-(define-key rmail-mode-map [menu-bar summary labels]
-  '("By Labels..." . rmail-summary-by-labels))
+    (define-key map [menu-bar summary labels]
+      '("By Labels..." . rmail-summary-by-labels))
 
-(define-key rmail-mode-map [menu-bar summary recipients]
-  '("By Recipients..." . rmail-summary-by-recipients))
+    (define-key map [menu-bar summary recipients]
+      '("By Recipients..." . rmail-summary-by-recipients))
 
-(define-key rmail-mode-map [menu-bar summary topic]
-  '("By Topic..." . rmail-summary-by-topic))
+    (define-key map [menu-bar summary topic]
+      '("By Topic..." . rmail-summary-by-topic))
 
-(define-key rmail-mode-map [menu-bar summary regexp]
-  '("By Regexp..." . rmail-summary-by-regexp))
+    (define-key map [menu-bar summary regexp]
+      '("By Regexp..." . rmail-summary-by-regexp))
 
-(define-key rmail-mode-map [menu-bar summary all]
-  '("All" . rmail-summary))
+    (define-key map [menu-bar summary all]
+      '("All" . rmail-summary))
 
-(define-key rmail-mode-map [menu-bar mail]
-  (cons "Mail" (make-sparse-keymap "Mail")))
+    (define-key map [menu-bar mail]
+      (cons "Mail" (make-sparse-keymap "Mail")))
 
-(define-key rmail-mode-map [menu-bar mail rmail-get-new-mail]
-  '("Get New Mail" . rmail-get-new-mail))
+    (define-key map [menu-bar mail rmail-get-new-mail]
+      '("Get New Mail" . rmail-get-new-mail))
 
-(define-key rmail-mode-map [menu-bar mail lambda]
-  '("----"))
+    (define-key map [menu-bar mail lambda]
+      '("----"))
 
-(define-key rmail-mode-map [menu-bar mail continue]
-  '("Continue" . rmail-continue))
+    (define-key map [menu-bar mail continue]
+      '("Continue" . rmail-continue))
 
-(define-key rmail-mode-map [menu-bar mail resend]
-  '("Re-send..." . rmail-resend))
+    (define-key map [menu-bar mail resend]
+    '(menu-item "Resend..." rmail-resend :keys "C-u f"))
 
-(define-key rmail-mode-map [menu-bar mail forward]
-  '("Forward" . rmail-forward))
+    (define-key map [menu-bar mail forward]
+      '("Forward" . rmail-forward))
 
-(define-key rmail-mode-map [menu-bar mail retry]
-  '("Retry" . rmail-retry-failure))
+    (define-key map [menu-bar mail retry]
+      '("Retry" . rmail-retry-failure))
 
-(define-key rmail-mode-map [menu-bar mail reply]
-  '("Reply" . rmail-reply))
+    (define-key map [menu-bar mail reply]
+      '("Reply" . rmail-reply))
 
-(define-key rmail-mode-map [menu-bar mail mail]
-  '("Mail" . rmail-mail))
+    (define-key map [menu-bar mail mail]
+      '("Mail" . rmail-mail))
 
-(define-key rmail-mode-map [menu-bar delete]
-  (cons "Delete" (make-sparse-keymap "Delete")))
+    (define-key map [menu-bar delete]
+      (cons "Delete" (make-sparse-keymap "Delete")))
 
-(define-key rmail-mode-map [menu-bar delete expunge/save]
-  '("Expunge/Save" . rmail-expunge-and-save))
+    (define-key map [menu-bar delete expunge/save]
+      '("Expunge/Save" . rmail-expunge-and-save))
 
-(define-key rmail-mode-map [menu-bar delete expunge]
-  '("Expunge" . rmail-expunge))
+    (define-key map [menu-bar delete expunge]
+      '("Expunge" . rmail-expunge))
 
-(define-key rmail-mode-map [menu-bar delete undelete]
-  '("Undelete" . rmail-undelete-previous-message))
+    (define-key map [menu-bar delete undelete]
+      '("Undelete" . rmail-undelete-previous-message))
 
-(define-key rmail-mode-map [menu-bar delete delete]
-  '("Delete" . rmail-delete-forward))
+    (define-key map [menu-bar delete delete]
+      '("Delete" . rmail-delete-forward))
 
-(define-key rmail-mode-map [menu-bar move]
-  (cons "Move" (make-sparse-keymap "Move")))
+    (define-key map [menu-bar move]
+      (cons "Move" (make-sparse-keymap "Move")))
 
-(define-key rmail-mode-map [menu-bar move search-back]
-  '("Search Back..." . rmail-search-backwards))
+    (define-key map [menu-bar move search-back]
+      '("Search Back..." . rmail-search-backwards))
 
-(define-key rmail-mode-map [menu-bar move search]
-  '("Search..." . rmail-search))
+    (define-key map [menu-bar move search]
+      '("Search..." . rmail-search))
 
-(define-key rmail-mode-map [menu-bar move previous]
-  '("Previous Nondeleted" . rmail-previous-undeleted-message))
+    (define-key map [menu-bar move previous]
+      '("Previous Nondeleted" . rmail-previous-undeleted-message))
 
-(define-key rmail-mode-map [menu-bar move next]
-  '("Next Nondeleted" . rmail-next-undeleted-message))
+    (define-key map [menu-bar move next]
+      '("Next Nondeleted" . rmail-next-undeleted-message))
 
-(define-key rmail-mode-map [menu-bar move last]
-  '("Last" . rmail-last-message))
+    (define-key map [menu-bar move last]
+      '("Last" . rmail-last-message))
 
-(define-key rmail-mode-map [menu-bar move first]
-  '("First" . rmail-first-message))
+    (define-key map [menu-bar move first]
+      '("First" . rmail-first-message))
 
-(define-key rmail-mode-map [menu-bar move previous]
-  '("Previous" . rmail-previous-message))
+    (define-key map [menu-bar move previous]
+      '("Previous" . rmail-previous-message))
 
-(define-key rmail-mode-map [menu-bar move next]
-  '("Next" . rmail-next-message))
+    (define-key map [menu-bar move next]
+      '("Next" . rmail-next-message))
+
+   map)
+  "Keymap used in Rmail mode.")
 
 ;; Rmail toolbar
 (defvar rmail-tool-bar-map
-  (if (display-graphic-p)
-      (let ((map (make-sparse-keymap)))
-       (tool-bar-local-item-from-menu 'rmail-get-new-mail "mail/inbox"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-next-undeleted-message "right-arrow"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-previous-undeleted-message "left-arrow"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-search "search"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-input "open"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-mail "mail/compose"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-reply "mail/reply-all"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-forward "mail/forward"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-delete-forward "close"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-output "mail/move"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-output-body-to-file "mail/save"
-                                      map rmail-mode-map)
-       (tool-bar-local-item-from-menu 'rmail-expunge "delete"
-                                      map rmail-mode-map)
-       map)))
+  (let ((map (make-sparse-keymap)))
+    (tool-bar-local-item-from-menu 'rmail-get-new-mail "mail/inbox"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-next-undeleted-message "right-arrow"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-previous-undeleted-message "left-arrow"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-search "search"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-input "open"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-mail "mail/compose"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-reply "mail/reply-all"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-forward "mail/forward"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-delete-forward "close"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-output "mail/move"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-output-body-to-file "mail/save"
+                                  map rmail-mode-map)
+    (tool-bar-local-item-from-menu 'rmail-expunge "delete"
+                                  map rmail-mode-map)
+    map))
 
 
 \f
@@ -1185,6 +1195,8 @@ Note:    it means the file has no messages in it.\n\^_")))
 (defun rmail-mode-kill-summary ()
   (if rmail-summary-buffer (kill-buffer rmail-summary-buffer)))
 
+(defvar rmail-enable-multibyte)         ; dynamically bound
+
 ;;;###autoload
 (defun rmail-mode ()
   "Rmail Mode is used by \\<rmail-mode-map>\\[rmail] for editing Rmail files.
@@ -1218,8 +1230,8 @@ Instead, these commands are available:
 \\[rmail-reply]        Reply to this message.  Like \\[rmail-mail] but initializes some fields.
 \\[rmail-retry-failure]        Send this message again.  Used on a mailer failure message.
 \\[rmail-forward]      Forward this message to another user.
-\\[rmail-output-to-rmail-file]       Output this message to an Rmail file (append it).
-\\[rmail-output]       Output this message to a Unix-format mail file (append it).
+\\[rmail-output]       Output (append) this message to another mail file.
+\\[rmail-output-as-seen]       Output (append) this message to file as it's displayed.
 \\[rmail-output-body-to-file]  Save message body to a file.  Default filename comes from Subject line.
 \\[rmail-input]        Input Rmail file.  Run Rmail on that file.
 \\[rmail-add-label]    Add label to message.  It will be displayed in the mode line.
@@ -1240,10 +1252,10 @@ Instead, these commands are available:
     (rmail-mode-2)
     (when (and finding-rmail-file
               (null coding-system-for-read)
-              default-enable-multibyte-characters)
+              (default-value 'enable-multibyte-characters))
       (let ((rmail-enable-multibyte t))
        (rmail-require-mime-maybe)
-       (rmail-convert-file)
+       (rmail-convert-file-maybe)
        (goto-char (point-max))
        (set-buffer-multibyte t)))
     (rmail-set-message-counters)
@@ -1267,33 +1279,106 @@ Instead, these commands are available:
   ;; No need to auto save RMAIL files in normal circumstances
   ;; because they contain no info except attribute changes
   ;; and deletion of messages.
-  ;; The one exception is when messages are copied into an Rmail mode buffer.
-  ;; rmail-output-to-rmail-file enables auto save when you do that.
+  ;; The one exception is when messages are copied into another mbox buffer.
+  ;; rmail-output enables auto save when you do that.
   (setq buffer-auto-save-file-name nil)
-  (setq mode-line-modified "--")
   (use-local-map rmail-mode-map)
   (set-syntax-table text-mode-syntax-table)
-  (setq local-abbrev-table text-mode-abbrev-table))
+  (setq local-abbrev-table text-mode-abbrev-table)
+  ;; Functions to support buffer swapping:
+  (add-hook 'write-region-annotate-functions
+           'rmail-write-region-annotate nil t)
+  (add-hook 'kill-buffer-hook 'rmail-mode-kill-buffer-hook nil t)
+  (add-hook 'change-major-mode-hook 'rmail-change-major-mode-hook nil t))
+
+(defun rmail-generate-viewer-buffer ()
+  "Return a reusable buffer suitable for viewing messages.
+Create the buffer if necessary."
+  (let* ((suffix (file-name-nondirectory (or buffer-file-name (buffer-name))))
+        (name (format " *message-viewer %s*" suffix))
+        (buf (get-buffer name)))
+    (or buf
+       (generate-new-buffer name))))
+
+(defun rmail-swap-buffers ()
+  "Swap text between current buffer and `rmail-view-buffer'.
+This function preserves the current buffer's modified flag, and also
+sets the current buffer's `buffer-file-coding-system' to that of
+`rmail-view-buffer'."
+  (let ((modp (buffer-modified-p))
+       (coding
+        (with-current-buffer rmail-view-buffer
+          buffer-file-coding-system)))
+    (buffer-swap-text rmail-view-buffer)
+    (setq buffer-file-coding-system coding)
+    (restore-buffer-modified-p modp)))
+
+(defun rmail-buffers-swapped-p ()
+  "Return non-nil if the message collection is in `rmail-view-buffer'."
+  ;; This is analogous to tar-data-swapped-p in tar-mode.el.
+  (and (buffer-live-p rmail-view-buffer)
+       rmail-buffer-swapped))
+
+(defun rmail-change-major-mode-hook ()
+  ;; Bring the actual Rmail messages back into the main buffer.
+  (when (rmail-buffers-swapped-p)
+    (rmail-swap-buffers)
+    (setq rmail-buffer-swapped nil)))
+
+(defun rmail-swap-buffers-maybe ()
+  "Determine if the Rmail buffer is showing a message.
+If so restore the actual mbox message collection."
+  (with-current-buffer rmail-buffer
+    (when (rmail-buffers-swapped-p)
+      (rmail-swap-buffers)
+      (setq rmail-buffer-swapped nil))))
+
+(defun rmail-modify-format ()
+  "Warn if important modifications would change Rmail file's format."
+  (with-current-buffer rmail-buffer
+    (and rmail-was-converted
+        ;; If it's already modified, don't warn again.
+        (not rmail-seriously-modified)
+        (not
+         (yes-or-no-p
+          (message "After this, %s would be saved in mbox format.  Proceed? "
+                   (buffer-name))))
+        (error "Aborted"))
+    (setq rmail-seriously-modified t)))
+
+(defun rmail-dont-modify-format ()
+  (when (and rmail-was-converted (not rmail-seriously-modified))
+    (set-buffer-modified-p nil)
+    (message "Marking buffer unmodified to avoid rewriting Babyl file as mbox file")))
+
+(defun rmail-mode-kill-buffer-hook ()
+  (if (buffer-live-p rmail-view-buffer) (kill-buffer rmail-view-buffer)))
 
 ;; Set up the permanent locals associated with an Rmail file.
 (defun rmail-perm-variables ()
-  (make-local-variable 'rmail-last-label)
   (make-local-variable 'rmail-last-regexp)
   (make-local-variable 'rmail-deleted-vector)
   (make-local-variable 'rmail-buffer)
+  (make-local-variable 'rmail-was-converted)
+  (setq rmail-was-converted nil)
+  (make-local-variable 'rmail-seriously-modified)
+  (setq rmail-seriously-modified nil)
   (setq rmail-buffer (current-buffer))
-  (make-local-variable 'rmail-view-buffer)
-  (setq rmail-view-buffer rmail-buffer)
+  (set-buffer-multibyte nil)
+  (with-current-buffer (setq rmail-view-buffer (rmail-generate-viewer-buffer))
+    (setq buffer-undo-list t)
+    (set (make-local-variable 'rmail-overlay-list) nil)
+    (set-buffer-multibyte t)
+    ;; Force C-x C-s write Unix EOLs.
+    (set-buffer-file-coding-system 'undecided-unix))
   (make-local-variable 'rmail-summary-buffer)
   (make-local-variable 'rmail-summary-vector)
   (make-local-variable 'rmail-current-message)
   (make-local-variable 'rmail-total-messages)
-  (make-local-variable 'rmail-overlay-list)
-  (setq rmail-overlay-list nil)
+  (setq rmail-total-messages 0)
   (make-local-variable 'rmail-message-vector)
   (make-local-variable 'rmail-msgref-vector)
   (make-local-variable 'rmail-inbox-list)
-  (setq rmail-inbox-list (rmail-parse-file-inboxes))
   ;; Provide default set of inboxes for primary mail file ~/RMAIL.
   (and (null rmail-inbox-list)
        (or (equal buffer-file-name (expand-file-name rmail-file-name))
@@ -1302,25 +1387,22 @@ Instead, these commands are available:
        (setq rmail-inbox-list
             (or rmail-primary-inbox-list
                 (list (or (getenv "MAIL")
+                          ;; FIXME expand-file-name?
                           (concat rmail-spool-directory
                                   (user-login-name)))))))
-  (make-local-variable 'rmail-keywords)
-  (set (make-local-variable 'tool-bar-map) rmail-tool-bar-map)
-  ;; this gets generated as needed
-  (setq rmail-keywords nil))
+  (set (make-local-variable 'tool-bar-map) rmail-tool-bar-map))
 
 ;; Set up the non-permanent locals associated with Rmail mode.
 (defun rmail-variables ()
-  (make-local-variable 'save-buffer-coding-system)
-  ;; If we don't already have a value for save-buffer-coding-system,
-  ;; get it from buffer-file-coding-system, and clear that
-  ;; because it should be determined in rmail-show-message.
-  (unless save-buffer-coding-system
-    (setq save-buffer-coding-system (or buffer-file-coding-system 'undecided))
-    (setq buffer-file-coding-system nil))
+  ;; Turn off undo.  We turn it back on in rmail-edit.
+  (setq buffer-undo-list t)
   ;; Don't let a local variables list in a message cause confusion.
   (make-local-variable 'local-enable-local-variables)
   (setq local-enable-local-variables nil)
+  ;; Don't turn off auto-saving based on the size of the buffer
+  ;; because that code does not understand buffer-swapping.
+  (make-local-variable 'auto-save-include-big-deletions)
+  (setq auto-save-include-big-deletions t)
   (make-local-variable 'revert-buffer-function)
   (setq revert-buffer-function 'rmail-revert)
   (make-local-variable 'font-lock-defaults)
@@ -1341,56 +1423,41 @@ Instead, these commands are available:
   (setq file-precious-flag t)
   (make-local-variable 'desktop-save-buffer)
   (setq desktop-save-buffer t))
-
+\f
 ;; Handle M-x revert-buffer done in an rmail-mode buffer.
 (defun rmail-revert (arg noconfirm)
   (set-buffer rmail-buffer)
   (let* ((revert-buffer-function (default-value 'revert-buffer-function))
         (rmail-enable-multibyte enable-multibyte-characters)
         ;; See similar code in `rmail'.
-        (coding-system-for-read (and rmail-enable-multibyte 'raw-text)))
+        ;; FIXME needs updating?
+        (coding-system-for-read (and rmail-enable-multibyte 'raw-text))
+        (before-revert-hook 'rmail-swap-buffers-maybe))
     ;; Call our caller again, but this time it does the default thing.
-    (if (revert-buffer arg noconfirm)
-       ;; If the user said "yes", and we changed something,
-       ;; reparse the messages.
-       (progn
-         (set-buffer rmail-buffer)
-         (rmail-mode-2)
-         ;; Convert all or part to Babyl file if possible.
-         (rmail-convert-file)
-         ;; We have read the file as raw-text, so the buffer is set to
-         ;; unibyte.  Make it multibyte if necessary.
-         (if (and rmail-enable-multibyte
-                  (not enable-multibyte-characters))
-             (set-buffer-multibyte t))
-         (goto-char (point-max))
-         (rmail-set-message-counters)
-         (rmail-show-message rmail-total-messages)
-         (run-hooks 'rmail-mode-hook)))))
-
-;; Return a list of files from this buffer's Mail: option.
-;; Does not assume that messages have been parsed.
-;; Just returns nil if buffer does not look like Babyl format.
-(defun rmail-parse-file-inboxes ()
-  (save-excursion
-    (save-restriction
-      (widen)
-      (goto-char 1)
-      (cond ((looking-at "BABYL OPTIONS:")
-            (search-forward "\n\^_" nil 'move)
-            (narrow-to-region 1 (point))
-            (goto-char 1)
-            (if (search-forward "\nMail:" nil t)
-                (progn
-                  (narrow-to-region (point) (progn (end-of-line) (point)))
-                  (goto-char (point-min))
-                  (mail-parse-comma-list))))))))
+    (when (revert-buffer arg noconfirm)
+      ;; If the user said "yes", and we changed something,
+      ;; reparse the messages.
+      (set-buffer rmail-buffer)
+      (rmail-mode-2)
+      ;; Convert all or part to Babyl file if possible.
+      (rmail-convert-file-maybe)
+      ;; We have read the file as raw-text, so the buffer is set to
+      ;; unibyte.  Make it multibyte if necessary.
+      (if (and rmail-enable-multibyte
+              (not enable-multibyte-characters))
+         (set-buffer-multibyte t))
+      (goto-char (point-max))
+      (rmail-set-message-counters)
+      (rmail-show-message rmail-total-messages)
+      (run-hooks 'rmail-mode-hook))))
 
 (defun rmail-expunge-and-save ()
   "Expunge and save RMAIL file."
   (interactive)
-  (rmail-expunge)
   (set-buffer rmail-buffer)
+  (rmail-expunge)
+  ;; No need to swap buffers: rmail-write-region-annotate takes care of it.
+  ;; (rmail-swap-buffers-maybe)
   (save-buffer)
   (if (rmail-summary-exists)
       (rmail-select-summary (set-buffer-modified-p nil))))
@@ -1399,11 +1466,15 @@ Instead, these commands are available:
   "Quit out of RMAIL.
 Hook `rmail-quit-hook' is run after expunging."
   (interactive)
-  (rmail-expunge-and-save)
+  (set-buffer rmail-buffer)
+  (rmail-expunge t)
+  (save-buffer)
   (when (boundp 'rmail-quit-hook)
     (run-hooks 'rmail-quit-hook))
   ;; Don't switch to the summary buffer even if it was recently visible.
   (when rmail-summary-buffer
+    (with-current-buffer rmail-summary-buffer
+      (set-buffer-modified-p nil))
     (replace-buffer-in-windows rmail-summary-buffer)
     (bury-buffer rmail-summary-buffer))
   (if rmail-enable-mime
@@ -1430,30 +1501,40 @@ Hook `rmail-quit-hook' is run after expunging."
            (quit-window nil window))
          (bury-buffer rmail-summary-buffer)))
     (quit-window)))
-
+\f
 (defun rmail-duplicate-message ()
   "Create a duplicated copy of the current message.
-The duplicate copy goes into the Rmail file just after the
-original copy."
-  (interactive)
-  (widen)
-  (let ((buffer-read-only nil)
-       (number rmail-current-message)
-       (string (buffer-substring (rmail-msgbeg rmail-current-message)
-                                 (rmail-msgend rmail-current-message))))
-    (goto-char (rmail-msgend rmail-current-message))
-    (insert string)
-    (rmail-forget-messages)
-    (rmail-show-message number)
-    (message "Message duplicated")))
-
+The duplicate copy goes into the Rmail file just after the original."
+  ;; If we are in a summary buffer, switch to the Rmail buffer.
+  ;; FIXME simpler to swap the contents, not the buffers?
+  (set-buffer rmail-buffer)
+  (rmail-modify-format)
+  (let ((buff (current-buffer))
+        (n rmail-current-message)
+        (beg (rmail-msgbeg rmail-current-message))
+        (end (rmail-msgend rmail-current-message)))
+    (if (rmail-buffers-swapped-p) (set-buffer rmail-view-buffer))
+      (widen)
+      (let ((buffer-read-only nil)
+          (string (buffer-substring-no-properties beg end)))
+      (goto-char end)
+      (insert string))
+    (set-buffer buff)
+    (rmail-swap-buffers-maybe)
+    (goto-char (point-max))
+    (rmail-set-message-counters)
+    (set-buffer-modified-p t)
+    (rmail-show-message-1 n))
+  (if (rmail-summary-exists)
+      (rmail-select-summary (rmail-update-summary)))
+  (message "Message duplicated"))
+\f
 ;;;###autoload
 (defun rmail-input (filename)
   "Run Rmail on file FILENAME."
   (interactive "FRun rmail on RMAIL file: ")
   (rmail filename))
 
-
 ;; This used to scan subdirectories recursively, but someone pointed out
 ;; that if the user wants that, person can put all the files in one dir.
 ;; And the recursive scan was slow.  So I took it out.
@@ -1469,32 +1550,31 @@ original copy."
        (sort files 'string<))))
 
 (defun rmail-list-to-menu (menu-name l action &optional full-name)
-  (let ((menu (make-sparse-keymap menu-name)))
+  (let ((menu (make-sparse-keymap menu-name))
+       name)
     (mapc
-     (function (lambda (item)
-                (let (command)
-                  (if (consp item)
-                      (progn
-                        (setq command
-                              (rmail-list-to-menu (car item) (cdr item)
-                                                  action
-                                                  (if full-name
-                                                      (concat full-name "/"
-                                                              (car item))
-                                                    (car item))))
-                        (setq name (car item)))
-                    (progn
-                      (setq name item)
-                      (setq command
-                            (list 'lambda () '(interactive)
-                                  (list action
-                                        (expand-file-name
-                                         (if full-name
-                                             (concat full-name "/" item)
-                                           item)
-                                         rmail-secondary-file-directory))))))
-                  (define-key menu (vector (intern name))
-                    (cons name command)))))
+     (lambda (item)
+       (let (command)
+        (if (consp item)
+            (setq command
+                  (rmail-list-to-menu
+                   (car item) (cdr item) action
+                   (if full-name
+                       (concat full-name "/"
+                               (car item))
+                     (car item)))
+                  name (car item))
+          (setq name item)
+          (setq command
+                (list 'lambda () '(interactive)
+                      (list action
+                            (expand-file-name
+                             (if full-name
+                                 (concat full-name "/" item)
+                               item)
+                             rmail-secondary-file-directory)))))
+        (define-key menu (vector (intern name))
+          (cons name command))))
      (reverse l))
     menu))
 
@@ -1514,7 +1594,7 @@ original copy."
            (cons "Output Rmail File"
                  (rmail-list-to-menu "Output Rmail File"
                                      files
-                                     'rmail-output-to-rmail-file))))
+                                     'rmail-output))))
 
       (define-key rmail-mode-map [menu-bar classify input-menu]
        '("Input Rmail File" . rmail-disable-menu))
@@ -1524,7 +1604,6 @@ original copy."
 \f
 ;;;; *** Rmail input ***
 
-(declare-function rmail-spam-filter "rmail-spam-filter" (msg))
 (declare-function rmail-summary-goto-msg "rmailsum" (&optional n nowarn skip-rmail))
 (declare-function rmail-summary-mark-undeleted "rmailsum" (n))
 (declare-function rmail-summary-mark-deleted "rmailsum" (&optional n undel))
@@ -1536,23 +1615,37 @@ original copy."
 ;; RLK feature not added in this version:
 ;; argument specifies inbox file or files in various ways.
 
+;; In Babyl, the Mail: header in the preamble overrode rmail-inbox-list.
+;; Mbox does not have this feature.
 (defun rmail-get-new-mail (&optional file-name)
-  "Move any new mail from this RMAIL file's inbox files.
-The inbox files can be specified with the file's Mail: option.  The
-variable `rmail-primary-inbox-list' specifies the inboxes for your
-primary RMAIL file if it has no Mail: option.  By default, this is
-your /usr/spool/mail/$USER.
-
-You can also specify the file to get new mail from.  In this case, the
-file of new mail is not changed or deleted.  Noninteractively, you can
-pass the inbox file name as an argument.  Interactively, a prefix
-argument causes us to read a file name and use that file as the inbox.
+  "Move any new mail from this Rmail file's inbox files.
+The buffer-local variable `rmail-inbox-list' specifies the list
+of inbox files.  By default, this is nil, except for your primary
+Rmail file `rmail-file-name'.  In this case, when you first visit
+the Rmail file it is initialized using either
+`rmail-primary-inbox-list', or the \"MAIL\" environment variable,
+or the function `user-login-name' and the directory
+`rmail-spool-directory' (whose value depends on the operating system).
+
+The command `set-rmail-inbox-list' sets `rmail-inbox-list' to the
+value you specify.
+
+You can also specify the file to get new mail from just for one
+instance of this command.  In this case, the file of new mail is
+not changed or deleted.  Noninteractively, you can pass the inbox
+file name as an argument.  Interactively, a prefix argument
+causes us to read a file name and use that file as the inbox.
 
 If the variable `rmail-preserve-inbox' is non-nil, new mail will
 always be left in inbox files rather than deleted.
 
-This function runs `rmail-get-new-mail-hook' before saving the updated file.
-It returns t if it got any new messages."
+Before doing anything, this runs `rmail-before-get-new-mail-hook'.
+Just before returning, it runs `rmail-after-get-new-mail-hook',
+whether or not there is new mail.
+
+If there is new mail, it runs `rmail-get-new-mail-hook', saves
+the updated file, and shows the first unseen message (which might
+not be a new one).  It returns non-nil if it got any new messages."
   (interactive
    (list (if current-prefix-arg
             (read-file-name "Get new mail from file: "))))
@@ -1562,170 +1655,128 @@ It returns t if it got any new messages."
   (or (verify-visited-file-modtime (current-buffer))
       (find-file (buffer-file-name)))
   (set-buffer rmail-buffer)
+  (rmail-modify-format)
+  (rmail-swap-buffers-maybe)
   (rmail-maybe-set-message-counters)
   (widen)
   ;; Get rid of all undo records for this buffer.
   (or (eq buffer-undo-list t)
       (setq buffer-undo-list nil))
-  (let ((all-files (if file-name (list file-name)
-                    rmail-inbox-list))
+  (let ((all-files (if file-name (list file-name) rmail-inbox-list))
        (rmail-enable-multibyte (default-value 'enable-multibyte-characters))
        found)
     (unwind-protect
        (progn
+         ;; This loops if any members of the inbox list have the same
+         ;; basename (see "name conflict" below).
          (while all-files
            (let ((opoint (point))
-                 (new-messages 0)
-                 (rsf-number-of-spam 0)
-                 (delete-files ())
-                 ;; If buffer has not changed yet, and has not been saved yet,
-                 ;; don't replace the old backup file now.
-                 (make-backup-files (and make-backup-files (buffer-modified-p)))
+                 ;; If buffer has not changed yet, and has not been
+                 ;; saved yet, don't replace the old backup file now.
+                 (make-backup-files (and make-backup-files
+                                         (buffer-modified-p)))
                  (buffer-read-only nil)
-                 ;; Don't make undo records for what we do in getting mail.
+                 ;; Don't make undo records while getting mail.
                  (buffer-undo-list t)
-                 success
-                 ;; Files to insert this time around.
-                 files
-                 ;; Last names of those files.
-                 file-last-names)
-             ;; Pull files off all-files onto files
-             ;; as long as there is no name conflict.
-             ;; A conflict happens when two inbox file names
-             ;; have the same last component.
+                 delete-files success files file-last-names)
+             ;; Pull files off all-files onto files as long as there is
+             ;; no name conflict.  A conflict happens when two inbox
+             ;; file names have the same last component.
+             ;; The reason this careful handling is necessary seems
+             ;; to be that rmail-insert-inbox-text uses .newmail-BASENAME.
              (while (and all-files
                          (not (member (file-name-nondirectory (car all-files))
-                                      file-last-names)))
+                               file-last-names)))
                (setq files (cons (car all-files) files)
                      file-last-names
                      (cons (file-name-nondirectory (car all-files)) files))
                (setq all-files (cdr all-files)))
              ;; Put them back in their original order.
              (setq files (nreverse files))
-
+             ;; In case of brain damage caused by require-final-newline.
              (goto-char (point-max))
-             (skip-chars-backward " \t\n") ; just in case of brain damage
-             (delete-region (point) (point-max)) ; caused by require-final-newline
-             (save-excursion
-               (save-restriction
-                 (narrow-to-region (point) (point))
-                 ;; Read in the contents of the inbox files,
-                 ;; renaming them as necessary,
-                 ;; and adding to the list of files to delete eventually.
-                 (if file-name
-                     (rmail-insert-inbox-text files nil)
-                   (setq delete-files (rmail-insert-inbox-text files t)))
-                 ;; Scan the new text and convert each message to babyl format.
-                 (goto-char (point-min))
-                 (unwind-protect
-                     (save-excursion
-                       (setq new-messages (rmail-convert-to-babyl-format)
-                             success t))
-                   ;; Try to delete the garbage just inserted.
-                   (or success (delete-region (point-min) (point-max)))
-                   ;; If we could not convert the file's inboxes,
-                   ;; rename the files we tried to read
-                   ;; so we won't over and over again.
-                   (if (and (not file-name) (not success))
-                       (let ((delfiles delete-files)
-                             (count 0))
-                         (while delfiles
-                           (while (file-exists-p (format "RMAILOSE.%d" count))
-                             (setq count (1+ count)))
-                           (rename-file (car delfiles)
-                                        (format "RMAILOSE.%d" count))
-                           (setq delfiles (cdr delfiles))))))
-                 (or (zerop new-messages)
-                     (let (success)
-                       (widen)
-                       (search-backward "\n\^_" nil t)
-                       (narrow-to-region (point) (point-max))
-                       (goto-char (1+ (point-min)))
-                       (rmail-count-new-messages)
-                       (run-hooks 'rmail-get-new-mail-hook)
-                       (save-buffer)))
-                 ;; Delete the old files, now that babyl file is saved.
-                 (while delete-files
-                   (condition-case ()
-                       ;; First, try deleting.
-                       (condition-case ()
-                           (delete-file (car delete-files))
-                         (file-error
-                          ;; If we can't delete it, truncate it.
-                          (write-region (point) (point) (car delete-files))))
-                     (file-error nil))
-                   (setq delete-files (cdr delete-files)))))
-             (if (= new-messages 0)
-                 (progn (goto-char opoint)
-                        (if (or file-name rmail-inbox-list)
-                            (message "(No new mail has arrived)")))
-               ;; check new messages to see if any of them is spam:
-               (if (and (featurep 'rmail-spam-filter)
-                        rmail-use-spam-filter)
-                   (let*
-                       ((old-messages (- rmail-total-messages new-messages))
-                         (rsf-scanned-message-number (1+ old-messages))
-                         ;; save deletion flags of old messages: vector starts
-                         ;; at zero (is one longer that no of messages),
-                         ;; therefore take 1+ old-messages
-                         (save-deleted
-                          (substring rmail-deleted-vector 0 (1+
-                          old-messages))))
-                      ;; set all messages to undeleted
-                      (setq rmail-deleted-vector
-                            (make-string (1+ rmail-total-messages) ?\ ))
-                     (while (<= rsf-scanned-message-number
-                     rmail-total-messages)
-                       (progn
-                         (if (not (rmail-spam-filter rsf-scanned-message-number))
-                             (progn (setq rsf-number-of-spam (1+ rsf-number-of-spam)))
-                           )
-                         (setq rsf-scanned-message-number (1+ rsf-scanned-message-number))
-                         ))
-                     (if (> rsf-number-of-spam 0)
-                         (progn
-                           (when (rmail-expunge-confirmed)
-                              (rmail-only-expunge t))
-                            ))
-                      (setq rmail-deleted-vector
-                            (concat
-                             save-deleted
-                             (make-string (- rmail-total-messages old-messages)
-                                          ?\ )))
-                     ))
-               (if (rmail-summary-exists)
-                   (rmail-select-summary
-                    (rmail-update-summary)))
-               (message "%d new message%s read%s"
-                        new-messages (if (= 1 new-messages) "" "s")
-                        ;; print out a message on number of spam messages found:
-                        (if (and (featurep 'rmail-spam-filter)
-                                 rmail-use-spam-filter
-                                 (> rsf-number-of-spam 0))
-                            (cond ((= 1 new-messages)
-                                   ", and appears to be spam")
-                                  ((= rsf-number-of-spam new-messages)
-                                   ", and all appear to be spam")
-                                  ((> rsf-number-of-spam 1)
-                                   (format ", and %d appear to be spam"
-                                           rsf-number-of-spam))
-                                  (t
-                                   ", and 1 appears to be spam"))
-                          ""))
-               (if (and (featurep 'rmail-spam-filter)
-                        rmail-use-spam-filter
-                        (> rsf-number-of-spam 0))
-                   (progn (if rsf-beep (beep t))
-                          (sleep-for rsf-sleep-after-message)))
-
-               ;; Move to the first new message
-               ;; unless we have other unseen messages before it.
-               (rmail-show-message (rmail-first-unseen-message))
-               (run-hooks 'rmail-after-get-new-mail-hook)
-               (setq found t))))
+             (skip-chars-backward " \t\n")
+             (delete-region (point) (point-max))
+             (setq found (or
+                          (rmail-get-new-mail-1 file-name files delete-files)
+                          found))))
+         ;; Move to the first new message unless we have other unseen
+         ;; messages before it.
+         (if found (rmail-show-message (rmail-first-unseen-message)))
+         (run-hooks 'rmail-after-get-new-mail-hook)
          found)
       ;; Don't leave the buffer screwed up if we get a disk-full error.
-      (or found (rmail-show-message)))))
+      (rmail-show-message))))
+
+(defvar rmail-use-spam-filter)
+(declare-function rmail-get-new-mail-filter-spam "rmail-spam-filter" (nnew))
+
+(defun rmail-get-new-mail-1 (file-name files delete-files)
+  "Return t if new messages are detected without error, nil otherwise."
+  (save-excursion
+    (save-restriction
+      (let ((new-messages 0)
+           (spam-filter-p (and (featurep 'rmail-spam-filter)
+                               rmail-use-spam-filter))
+           (blurb "")
+           result success suffix)
+       (narrow-to-region (point) (point))
+       ;; Read in the contents of the inbox files, renaming them as
+       ;; necessary, and adding to the list of files to delete
+       ;; eventually.
+       (if file-name
+           (rmail-insert-inbox-text files nil)
+         (setq delete-files (rmail-insert-inbox-text files t)))
+       ;; Scan the new text and convert each message to
+       ;; Rmail/mbox format.
+       (goto-char (point-min))
+       (skip-chars-forward " \n")
+       (narrow-to-region (point) (point-max))
+       (unwind-protect
+           (setq new-messages (rmail-add-mbox-headers)
+                 success t)
+         ;; Try to delete the garbage just inserted.
+         (or success (delete-region (point-min) (point-max)))
+         ;; If we could not convert the file's inboxes, rename the
+         ;; files we tried to read so we won't over and over again.
+         (if (and (not file-name) (not success))
+             (let ((delfiles delete-files)
+                   (count 0))
+               (while delfiles
+                 (while (file-exists-p (format "RMAILOSE.%d" count))
+                   (setq count (1+ count)))
+                 (rename-file (car delfiles) (format "RMAILOSE.%d" count))
+                 (setq delfiles (cdr delfiles))))))
+       ;; Determine if there are messages.
+       (unless (zerop new-messages)
+         ;; There are.  Process them.
+         (goto-char (point-min))
+         (rmail-count-new-messages)
+         (run-hooks 'rmail-get-new-mail-hook)
+         (save-buffer))
+       ;; Delete the old files, now that the Rmail file is saved.
+       (while delete-files
+         (condition-case ()
+             ;; First, try deleting.
+             (condition-case ()
+                 (delete-file (car delete-files))
+               (file-error
+                ;; If we can't delete it, truncate it.
+                (write-region (point) (point) (car delete-files))))
+           (file-error nil))
+         (setq delete-files (cdr delete-files)))
+       (if (zerop new-messages)
+           (when (or file-name rmail-inbox-list)
+             (message "(No new mail has arrived)"))
+         (if spam-filter-p
+             (setq blurb (rmail-get-new-mail-filter-spam new-messages))))
+       (if (rmail-summary-exists)
+           (rmail-select-summary (rmail-update-summary)))
+       (setq suffix (if (= 1 new-messages) "" "s"))
+       (message "%d new message%s read%s" new-messages suffix blurb)
+       ;; Establish the return value.
+       (setq result (> new-messages 0))
+       result))))
 
 (defun rmail-parse-url (file)
   "Parse the supplied URL. Return (list MAILBOX-NAME REMOTE PASSWORD GOT-PASSWORD)
@@ -1748,7 +1799,10 @@ is non-nil if the user has supplied the password interactively.
            (when rmail-remote-password-required
              (setq got-password (not (rmail-have-password)))
              (setq supplied-password (rmail-get-remote-password
-                                      (string-equal proto "imap")))))
+                                      (string-equal proto "imap"))))
+         ;; The password is embedded.  Strip it out since movemail
+         ;; does not really like it, in spite of the movemail spec.
+         (setq file (concat proto "://" user "@" host)))
 
        (if (rmail-movemail-variant-p 'emacs)
            (if (string-equal proto "pop")
@@ -1759,7 +1813,7 @@ is non-nil if the user has supplied the password interactively.
              (error "Emacs movemail does not support %s protocol" proto))
          (list file
                (or (string-equal proto "pop") (string-equal proto "imap"))
-               supplied-password
+               (or supplied-password pass)
                got-password))))
 
    ((string-match "^po:\\([^:]+\\)\\(:\\(.*\\)\\)?" file)
@@ -1777,6 +1831,49 @@ is non-nil if the user has supplied the password interactively.
    (t
     (list file nil nil nil))))
 
+(defun rmail-unrmail-new-mail (from-file)
+  "Replace newly read mail in Babyl format with equivalent mbox format.
+
+FROM-FILE is the Babyl file from which the new mail should be read."
+  (let ((to-file (make-temp-file "rmail"))
+       size)
+    (unrmail from-file to-file)
+    (let ((inhibit-read-only t)
+         (coding-system-for-read 'raw-text)
+         (buffer-undo-list t))
+      (delete-region (point) (point-max))
+      (setq size (nth 1 (insert-file-contents to-file)))
+      (delete-file to-file)
+      size)))
+
+(defun rmail-unrmail-new-mail-maybe (file size)
+  "If newly read mail from FILE is in Babyl format, convert it to mbox format.
+
+SIZE is the original size of the newly read mail.
+Value is the size of the newly read mail after conversion."
+  ;; Detect previous Babyl format files.
+  (let ((case-fold-search nil)
+       (old-file file)
+       new-file)
+    (cond ((looking-at "BABYL OPTIONS:")
+          ;; The new mail is in Babyl version 5 format.  Use unrmail
+          ;; to convert it.
+          (setq size (rmail-unrmail-new-mail old-file)))
+         ((looking-at "Version: 5\n")
+          ;; New mail is in Babyl format made by old version of
+          ;; Rmail.  Fix the babyl file header and use unrmail to
+          ;; convert it.
+          (let ((buffer-read-only nil)
+                (write-region-annotate-functions nil)
+                (write-region-post-annotation-function nil)
+                (old-file  (make-temp-file "rmail")))
+            (insert "BABYL OPTIONS: -*- rmail -*-\n")
+            (forward-line -1)
+            (write-region (point) (point-max) old-file)
+            (setq size (rmail-unrmail-new-mail old-file))
+            (delete-file old-file))))
+    size))
+
 (defun rmail-insert-inbox-text (files renamep)
   ;; Detect a locked file now, so that we avoid moving mail
   ;; out of the real inbox file.  (That could scare people.)
@@ -1815,13 +1912,12 @@ is non-nil if the user has supplied the password interactively.
                     (expand-file-name buffer-file-name))))
       ;; Always use movemail to rename the file,
       ;; since there can be mailboxes in various directories.
-      (if (not popmail)
-         (progn
-           ;; On some systems, /usr/spool/mail/foo is a directory
-           ;; and the actual inbox is /usr/spool/mail/foo/foo.
-           (if (file-directory-p file)
-               (setq file (expand-file-name (user-login-name)
-                                            file)))))
+      (when (not popmail)
+       ;; On some systems, /usr/spool/mail/foo is a directory
+       ;; and the actual inbox is /usr/spool/mail/foo/foo.
+       (if (file-directory-p file)
+           (setq file (expand-file-name (user-login-name)
+                                        file))))
       (cond (popmail
             (message "Getting mail from the remote server ..."))
            ((and (file-exists-p tofile)
@@ -1843,7 +1939,7 @@ is non-nil if the user has supplied the password interactively.
                 (buffer-disable-undo errors)
                 (let ((args
                        (append
-                        (list rmail-movemail-program nil errors nil)
+                        (list (or rmail-movemail-program "movemail") nil errors nil)
                         (if rmail-preserve-inbox
                             (list "-p")
                           nil)
@@ -1858,7 +1954,7 @@ is non-nil if the user has supplied the password interactively.
                     nil
                   (set-buffer errors)
                   (subst-char-in-region (point-min) (point-max)
-                                        ?\n ?\  )
+                                        ?\n ?\s)
                   (goto-char (point-max))
                   (skip-chars-backward " \t")
                   (delete-region (point) (point-max))
@@ -1895,7 +1991,23 @@ is non-nil if the user has supplied the password interactively.
          (let ((coding-system-for-read 'no-conversion)
                size)
            (goto-char (point-max))
-           (setq size (nth 1 (insert-file-contents tofile)))
+           (setq size
+                 ;; If new mail is in Babyl format, convert it to mbox.
+                 (rmail-unrmail-new-mail-maybe
+                  tofile
+                  (nth 1 (insert-file-contents tofile))))
+           ;; Determine if a pair of newline message separators need
+           ;; to be added to the new collection of messages.  This is
+           ;; the case for all new message collections added to a
+           ;; non-empty mail file.
+           (unless (zerop size)
+             (save-restriction
+               (let ((start (point-min)))
+                 (widen)
+                 (unless (eq start (point-min))
+                   (goto-char start)
+                   (insert "\n\n")
+                   (setq size (+ 2 size))))))
            (goto-char (point-max))
            (or (= (preceding-char) ?\n)
                (zerop size)
@@ -1908,620 +2020,173 @@ is non-nil if the user has supplied the password interactively.
 
 ;; Decode the region specified by FROM and TO by CODING.
 ;; If CODING is nil or an invalid coding system, decode by `undecided'.
-(defun rmail-decode-region (from to coding)
+(defun rmail-decode-region (from to coding &optional destination)
   (if (or (not coding) (not (coding-system-p coding)))
       (setq coding 'undecided))
   ;; Use -dos decoding, to remove ^M characters left from base64 or
   ;; rogue qp-encoded text.
-  (decode-coding-region from to
-                       (coding-system-change-eol-conversion coding 1))
+  (decode-coding-region
+   from to (coding-system-change-eol-conversion coding 1) destination)
   ;; Don't reveal the fact we used -dos decoding, as users generally
   ;; will not expect the RMAIL buffer to use DOS EOL format.
-  (setq buffer-file-coding-system
-       (setq last-coding-system-used
-             (coding-system-change-eol-conversion coding 0))))
-
-;; the  rmail-break-forwarded-messages  feature is not implemented
-(defun rmail-convert-to-babyl-format ()
-  (let ((count 0) start
-       (case-fold-search nil)
-       (buffer-undo-list t)
-       (invalid-input-resync
-        (function (lambda ()
-                    (message "Invalid Babyl format in inbox!")
-                    (sit-for 3)
-                    ;; Try to get back in sync with a real message.
-                    (if (re-search-forward
-                         (concat rmail-mmdf-delim1 "\\|^From") nil t)
-                        (beginning-of-line)
-                      (goto-char (point-max)))))))
-    (goto-char (point-min))
-    (save-restriction
-      (while (not (eobp))
-       (setq start (point))
-       (cond ((looking-at "BABYL OPTIONS:")    ;Babyl header
-              (if (search-forward "\n\^_" nil t)
-                  ;; If we find the proper terminator, delete through there.
-                  (delete-region (point-min) (point))
-                (funcall invalid-input-resync)
-                (delete-region (point-min) (point))))
-             ;; Babyl format message
-             ((looking-at "\^L")
-              (or (search-forward "\n\^_" nil t)
-                  (funcall invalid-input-resync))
-              (setq count (1+ count))
-              ;; Make sure there is no extra white space after the ^_
-              ;; at the end of the message.
-              ;; Narrowing will make sure that whatever follows the junk
-              ;; will be treated properly.
-              (delete-region (point)
-                             (save-excursion
-                               (skip-chars-forward " \t\n")
-                               (point)))
-              ;; The following let* form was wrapped in a `save-excursion'
-              ;; which in one case caused infinite looping, see:
-              ;; http://lists.gnu.org/archive/html/emacs-devel/2008-01/msg00968.html
-              ;; Removing that form leaves `point' at the end of the
-              ;; region decoded by `rmail-decode-region' which should
-              ;; be correct.
-              (let* ((header-end
-                      (progn
-                        (save-excursion
-                          (goto-char start)
-                          (forward-line 1)
-                          (if (looking-at "0")
-                              (forward-line 1)
-                            (forward-line 2))
-                          (save-restriction
-                            (narrow-to-region (point) (point-max))
-                            (rfc822-goto-eoh)
-                            (point)))))
-                     (case-fold-search t)
-                     (quoted-printable-header-field-end
-                      (save-excursion
-                        (goto-char start)
-                        (re-search-forward
-                         "^content-transfer-encoding:\\(\n?[\t ]\\)*quoted-printable\\(\n?[\t ]\\)*"
-                         header-end t)))
-                     (base64-header-field-end
-                      (save-excursion
-                        (goto-char start)
-                        ;; Don't try to decode non-text data.
-                        (and (re-search-forward
-                              "^content-type:\\(\n?[\t ]\\)\\(text\\|message\\)/"
-                              header-end t)
-                             (goto-char start)
-                             (re-search-forward
-                              "^content-transfer-encoding:\\(\n?[\t ]\\)*base64\\(\n?[\t ]\\)*"
-                              header-end t)))))
-                (if quoted-printable-header-field-end
-                    (save-excursion
-                      (unless
-                          (mail-unquote-printable-region header-end (point) nil t t)
-                        (message "Malformed MIME quoted-printable message"))
-                      ;; Change "quoted-printable" to "8bit",
-                      ;; to reflect the decoding we just did.
-                      (goto-char quoted-printable-header-field-end)
-                      (delete-region (point) (search-backward ":"))
-                      (insert ": 8bit")))
-                (if base64-header-field-end
-                    (save-excursion
-                      (when
-                          (condition-case nil
-                              (progn
-                                (base64-decode-region (1+ header-end)
-                                                      (- (point) 2))
-                                t)
-                            (error nil))
-                        ;; Change "base64" to "8bit", to reflect the
-                        ;; decoding we just did.
-                        (goto-char base64-header-field-end)
-                        (delete-region (point) (search-backward ":"))
-                        (insert ": 8bit"))))
-                (setq last-coding-system-used nil)
-                (or rmail-enable-mime
-                    (not rmail-enable-multibyte)
-                    (let ((mime-charset
-                           (if (and rmail-decode-mime-charset
-                                    (save-excursion
-                                      (goto-char start)
-                                      (search-forward "\n\n" nil t)
-                                      (let ((case-fold-search t))
-                                        (re-search-backward
-                                         rmail-mime-charset-pattern
-                                         start t))))
-                               (intern (downcase (match-string 1))))))
-                      (rmail-decode-region start (point) mime-charset))))
-              ;; Add an X-Coding-System: header if we don't have one.
-              (save-excursion
-                (goto-char start)
-                (forward-line 1)
-                (if (looking-at "0")
-                    (forward-line 1)
-                  (forward-line 2))
-                (or (save-restriction
-                      (narrow-to-region (point) (point-max))
-                      (rfc822-goto-eoh)
-                      (goto-char (point-min))
-                      (re-search-forward "^X-Coding-System:" nil t))
-                    (insert "X-Coding-System: "
-                            (symbol-name last-coding-system-used)
-                            "\n")))
-              (narrow-to-region (point) (point-max))
-              (and (= 0 (% count 10))
-                   (message "Converting to Babyl format...%d" count)))
-             ;;*** MMDF format
-             ((let ((case-fold-search t))
-                (looking-at rmail-mmdf-delim1))
-              (let ((case-fold-search t))
-                (replace-match "\^L\n0, unseen,,\n*** EOOH ***\n")
-                (re-search-forward rmail-mmdf-delim2 nil t)
-                (replace-match "\^_"))
-              (save-excursion
-                (save-restriction
-                  (narrow-to-region start (1- (point)))
-                  (goto-char (point-min))
-                  (while (search-forward "\n\^_" nil t) ; single char "\^_"
-                    (replace-match "\n^_"))))  ; 2 chars: "^" and "_"
-              (setq last-coding-system-used nil)
-              (or rmail-enable-mime
-                  (not rmail-enable-multibyte)
-                  (decode-coding-region start (point) 'undecided))
-              (save-excursion
-                (goto-char start)
-                (forward-line 3)
-                (insert "X-Coding-System: "
-                        (symbol-name last-coding-system-used)
-                        "\n"))
-              (narrow-to-region (point) (point-max))
-              (setq count (1+ count))
-              (and (= 0 (% count 10))
-                   (message "Converting to Babyl format...%d" count)))
-             ;;*** Mail format
-             ((looking-at "^From ")
-              (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
-              (rmail-nuke-pinhead-header)
-              ;; If this message has a Content-Length field,
-              ;; skip to the end of the contents.
-              (let* ((header-end (save-excursion
-                                   (and (re-search-forward "\n\n" nil t)
-                                        (1- (point)))))
-                     (case-fold-search t)
-                     (quoted-printable-header-field-end
-                      (save-excursion
-                        (re-search-forward
-                         "^content-transfer-encoding:\\(\n?[\t ]\\)*quoted-printable\\(\n?[\t ]\\)*"
-                         header-end t)))
-                     (base64-header-field-end
-                      (and
-                       ;; Don't decode non-text data.
-                       (save-excursion
-                         (re-search-forward
-                          "^content-type:\\(\n?[\t ]\\)\\(text\\|message\\)/"
-                          header-end t))
-                       (save-excursion
-                         (re-search-forward
-                          "^content-transfer-encoding:\\(\n?[\t ]\\)*base64\\(\n?[\t ]\\)*"
-                          header-end t))))
-                     (size
-                      ;; Get the numeric value from the Content-Length field.
-                      (save-excursion
-                        ;; Back up to end of prev line,
-                        ;; in case the Content-Length field comes first.
-                        (forward-char -1)
-                        (and (search-forward "\ncontent-length: "
-                                             header-end t)
-                             (let ((beg (point))
-                                   (eol (progn (end-of-line) (point))))
-                               (string-to-number (buffer-substring beg eol)))))))
-                (and size
-                     (if (and (natnump size)
-                              (<= (+ header-end size) (point-max))
-                              ;; Make sure this would put us at a position
-                              ;; that we could continue from.
-                              (save-excursion
-                                (goto-char (+ header-end size))
-                                (skip-chars-forward "\n")
-                                (or (eobp)
-                                    (and (looking-at "BABYL OPTIONS:")
-                                         (search-forward "\n\^_" nil t))
-                                    (and (looking-at "\^L")
-                                         (search-forward "\n\^_" nil t))
-                                    (let ((case-fold-search t))
-                                      (looking-at rmail-mmdf-delim1))
-                                    (looking-at "From "))))
-                         (goto-char (+ header-end size))
-                       (message "Ignoring invalid Content-Length field")
-                       (sit-for 1 0 t)))
-                (if (let ((case-fold-search nil))
-                      (re-search-forward
-                       (concat "^[\^_]?\\("
-                               rmail-unix-mail-delimiter
-                               "\\|"
-                               rmail-mmdf-delim1 "\\|"
-                               "^BABYL OPTIONS:\\|"
-                               "\^L\n[01],\\)") nil t))
-                    (goto-char (match-beginning 1))
-                  (goto-char (point-max)))
-                (setq count (1+ count))
-                (if quoted-printable-header-field-end
-                    (save-excursion
-                      (unless
-                          (mail-unquote-printable-region header-end (point) nil t t)
-                        (message "Malformed MIME quoted-printable message"))
-                      ;; Change "quoted-printable" to "8bit",
-                      ;; to reflect the decoding we just did.
-                      (goto-char quoted-printable-header-field-end)
-                      (delete-region (point) (search-backward ":"))
-                      (insert ": 8bit")))
-                (if base64-header-field-end
-                    (save-excursion
-                      (when
-                          (condition-case nil
-                              (progn
-                                (base64-decode-region
-                                 (1+ header-end)
-                                 (save-excursion
-                                   ;; Prevent base64-decode-region
-                                   ;; from removing newline characters.
-                                   (skip-chars-backward "\n\t ")
-                                   (point)))
-                                t)
-                            (error nil))
-                        ;; Change "base64" to "8bit", to reflect the
-                        ;; decoding we just did.
-                        (goto-char base64-header-field-end)
-                        (delete-region (point) (search-backward ":"))
-                        (insert ": 8bit")))))
-
-              (save-excursion
-                (save-restriction
-                  (narrow-to-region start (point))
-                  (goto-char (point-min))
-                  (while (search-forward "\n\^_" nil t) ; single char
-                    (replace-match "\n^_"))))  ; 2 chars: "^" and "_"
-              ;; This is for malformed messages that don't end in newline.
-              ;; There shouldn't be any, but some users say occasionally
-              ;; there are some.
-              (or (bolp) (newline))
-              (insert ?\^_)
-              (setq last-coding-system-used nil)
-              (or rmail-enable-mime
-                  (not rmail-enable-multibyte)
-                  (let ((mime-charset
-                         (if (and rmail-decode-mime-charset
-                                  (save-excursion
-                                    (goto-char start)
-                                    (search-forward "\n\n" nil t)
-                                    (let ((case-fold-search t))
-                                      (re-search-backward
-                                       rmail-mime-charset-pattern
-                                       start t))))
-                             (intern (downcase (match-string 1))))))
-                    (rmail-decode-region start (point) mime-charset)))
-              (save-excursion
-                (goto-char start)
-                (forward-line 3)
-                (insert "X-Coding-System: "
-                        (symbol-name last-coding-system-used)
-                        "\n"))
-              (narrow-to-region (point) (point-max))
-              (and (= 0 (% count 10))
-                   (message "Converting to Babyl format...%d" count)))
-             ;;
-             ;; This kludge is because some versions of sendmail.el
-             ;; insert an extra newline at the beginning that shouldn't
-             ;; be there.  sendmail.el has been fixed, but old versions
-             ;; may still be in use.  -- rms, 7 May 1993.
-             ((eolp) (delete-char 1))
-             (t (error "Cannot convert to babyl format")))))
-    (setq buffer-undo-list nil)
-    count))
-
-;; Delete the "From ..." line, creating various other headers with
-;; information from it if they don't already exist.  Now puts the
-;; original line into a mail-from: header line for debugging and for
-;; use by the rmail-output function.
-(defun rmail-nuke-pinhead-header ()
+  (cond
+   ((null destination)
+    (setq buffer-file-coding-system
+         (setq last-coding-system-used
+               (coding-system-change-eol-conversion coding 0))))
+   ((bufferp destination)
+    (with-current-buffer destination
+      (setq buffer-file-coding-system
+           (setq last-coding-system-used
+                 (coding-system-change-eol-conversion coding 0)))))))
+
+(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")))
+
+(defun rmail-add-mbox-headers ()
+  "Validate the RFC2822 format for the new messages.
+Point should be at the first new message.
+An error is signalled if the new messages are not RFC2822
+compliant.
+Unless an Rmail attribute header already exists, add it to the
+new messages.  Return the number of new messages."
   (save-excursion
     (save-restriction
-      (let ((start (point))
-           (end (progn
-                  (condition-case ()
-                      (search-forward "\n\n")
-                    (error
-                     (goto-char (point-max))
-                     (insert "\n\n")))
-                  (point)))
-           has-from has-date)
-       (narrow-to-region start end)
-       (let ((case-fold-search t))
-         (goto-char start)
-         (setq has-from (search-forward "\nFrom:" nil t))
-         (goto-char start)
-         (setq has-date (and (search-forward "\nDate:" nil t) (point)))
-         (goto-char start))
-       (let ((case-fold-search nil))
-         (if (re-search-forward (concat "^" rmail-unix-mail-delimiter) nil t)
-             (replace-match
-               (concat
-                 "Mail-from: \\&"
-                 ;; Keep and reformat the date if we don't
-                 ;;  have a Date: field.
-                 (if has-date
-                     ""
-                   (concat
-                    "Date: \\2, \\4 \\3 \\9 \\5 "
-
-                    ;; The timezone could be matched by group 7 or group 10.
-                    ;; If neither of them matched, assume EST, since only
-                    ;; Easterners would be so sloppy.
-                    ;; It's a shame the substitution can't use "\\10".
-                    (cond
-                     ((/= (match-beginning 7) (match-end 7)) "\\7")
-                     ((/= (match-beginning 10) (match-end 10))
-                      (buffer-substring (match-beginning 10)
-                                        (match-end 10)))
-                     (t "EST"))
-                    "\n"))
-                 ;; Keep and reformat the sender if we don't
-                 ;; have a From: field.
-                 (if has-from
-                     ""
-                   "From: \\1\n"))
-               t)))))))
+      (let ((count 0)
+           (start (point))
+           (value "------U-")
+           (case-fold-search nil)
+           (delim (concat "\n\n" rmail-unix-mail-delimiter))
+           limit stop)
+       ;; Detect an empty inbox file.
+       (unless (= start (point-max))
+         ;; Scan the new messages to establish a count and to ensure that
+         ;; an attribute header is present.
+         (if (looking-at rmail-unix-mail-delimiter)
+             (while (not stop)
+               ;; Determine if a new attribute header needs to be
+               ;; added to the message.
+               (if (search-forward "\n\n" nil t)
+                   (progn
+                     (setq count (1+ count))
+                     (narrow-to-region start (point))
+                     (unless (mail-fetch-field rmail-attribute-header)
+                       (backward-char 1)
+                       (insert rmail-attribute-header ": " value "\n"))
+                     (widen))
+                 (rmail-error-bad-format))
+               ;; Move to the next message.
+               (if (not (re-search-forward delim nil 'move))
+                   (setq stop t)
+                 (goto-char (match-beginning 0))
+                 (forward-char 2))
+               (setq start (point)))
+           (rmail-error-bad-format)))
+       count))))
 \f
-;;;; *** Rmail Message Formatting and Header Manipulation ***
-
-(defun rmail-reformat-message (beg end)
-  (goto-char beg)
-  (forward-line 1)
-  (if (/= (following-char) ?0)
-      (error "Bad format in RMAIL file"))
-  (let ((inhibit-read-only t)
-       (delta (- (buffer-size) end)))
-    (delete-char 1)
-    (insert ?1)
-    (forward-line 1)
-    (let ((case-fold-search t))
-      (while (looking-at "Summary-line:\\|Mail-From:")
-       (forward-line 1)))
-    (if (looking-at "\\*\\*\\* EOOH \\*\\*\\*\n")
-       (delete-region (point)
-                      (progn (forward-line 1) (point))))
-    (let ((str (buffer-substring (point)
-                                (save-excursion (search-forward "\n\n" end 'move)
-                                                (point)))))
-      (insert str "*** EOOH ***\n")
-      (narrow-to-region (point) (- (buffer-size) delta)))
-    (goto-char (point-min))
-    (if rmail-message-filter (funcall rmail-message-filter))
-    (if (or rmail-displayed-headers rmail-ignored-headers)
-       (rmail-clear-headers))))
-
-(defun rmail-clear-headers (&optional ignored-headers)
-  "Delete all header fields that Rmail should not show.
-If the optional argument IGNORED-HEADERS is non-nil,
-delete all header fields whose names match that regexp.
-Otherwise, if `rmail-displayed-headers' is non-nil,
-delete all header fields *except* those whose names match that regexp.
-Otherwise, delete all header fields whose names match `rmail-ignored-headers'
-unless they also match `rmail-nonignored-headers'."
-  (when (search-forward "\n\n" nil t)
-    (forward-char -1)
-    (let ((case-fold-search t)
-         (buffer-read-only nil))
-      (if (and rmail-displayed-headers (null ignored-headers))
-         (save-restriction
-           (narrow-to-region (point-min) (point))
-           (let (lim next)
-             (goto-char (point-min))
-             (while (and (not (eobp))
-                         (save-excursion
-                           (if (re-search-forward "\n[^ \t]" nil t)
-                               (setq lim (match-beginning 0)
-                                     next (1+ lim))
-                             (setq lim nil next (point-max)))))
-               (if (save-excursion
-                     (re-search-forward rmail-displayed-headers lim t))
-                 (goto-char next)
-                 (delete-region (point) next))))
-           (goto-char (point-min)))
-       (or ignored-headers (setq ignored-headers rmail-ignored-headers))
-       (save-restriction
-         (narrow-to-region (point-min) (point))
-         (goto-char (point-min))
-         (while (and ignored-headers
-                     (re-search-forward ignored-headers nil t))
-           (beginning-of-line)
-           (if (and rmail-nonignored-headers
-                    (looking-at rmail-nonignored-headers))
-               (forward-line 1)
-             (delete-region (point)
-                            (save-excursion
-                              (if (re-search-forward "\n[^ \t]" nil t)
-                                  (1- (point))
-                                (point-max)))))))))))
-
-(defun rmail-msg-is-pruned ()
-  (rmail-maybe-set-message-counters)
-  (save-restriction
-    (narrow-to-region (rmail-msgbeg rmail-current-message) (point-max))
-    (save-excursion
-      (goto-char (point-min))
-      (forward-line 1)
-      (= (following-char) ?1))))
-
-(defun rmail-msg-restore-non-pruned-header ()
-  (let ((old-point (point))
-       new-point
-       new-start
-       (inhibit-read-only t))
-    (save-excursion
-      (narrow-to-region (rmail-msgbeg rmail-current-message) (point-max))
-      (goto-char (point-min))
-      (forward-line 1)
-      ;; Change 1 to 0.
-      (delete-char 1)
-      (insert ?0)
-      ;; Insert new EOOH line at the proper place.
-      (forward-line 1)
-      (let ((case-fold-search t))
-       (while (looking-at "Summary-Line:\\|Mail-From:")
-         (forward-line 1)))
-      (insert "*** EOOH ***\n")
-      (setq new-start (point))
-      ;; Delete the old reformatted header.
-      (forward-char -1)
-      (search-forward "\n*** EOOH ***\n")
-      (forward-line -1)
-      (let ((start (point)))
-       (search-forward "\n\n")
-       (if (and (<= start old-point)
-                (<= old-point (point)))
-           (setq new-point new-start))
-       (delete-region start (point)))
-      ;; Narrow to after the new EOOH line.
-      (narrow-to-region new-start (point-max)))
-    (if new-point
-       (goto-char new-point))))
-
-(defun rmail-msg-prune-header ()
-  (let ((new-point
-        (= (point) (point-min))))
-    (save-excursion
-      (narrow-to-region (rmail-msgbeg rmail-current-message) (point-max))
-      (rmail-reformat-message (point-min) (point-max)))
-    (if new-point
-       (goto-char (point-min)))))
-
-(defun rmail-toggle-header (&optional arg)
-  "Show original message header if pruned header currently shown, or vice versa.
-With argument ARG, show the message header pruned if ARG is greater than zero;
-otherwise, show it in full."
-  (interactive "P")
-  (let* ((pruned (with-current-buffer rmail-buffer
-                  (rmail-msg-is-pruned)))
-        (prune (if arg
-                   (> (prefix-numeric-value arg) 0)
-                 (not pruned))))
-    (if (eq pruned prune)
-       t
-      (set-buffer rmail-buffer)
-      (rmail-maybe-set-message-counters)
-      (if rmail-enable-mime
-         (let ((buffer-read-only nil))
-           (if pruned
-               (rmail-msg-restore-non-pruned-header)
-             (rmail-msg-prune-header))
-           (funcall rmail-show-mime-function))
-       (let* ((buffer-read-only nil)
-              (window (get-buffer-window (current-buffer)))
-              (at-point-min (= (point) (point-min)))
-              (all-headers-visible (= (window-start window) (point-min)))
-              (on-header
-               (save-excursion
-                 (and (not (search-backward "\n\n" nil t))
-                      (progn
-                        (end-of-line)
-                        (re-search-backward "^[-A-Za-z0-9]+:" nil t))
-                      (match-string 0))))
-              (old-screen-line
-               (rmail-count-screen-lines (window-start window) (point))))
-         (if pruned
-             (rmail-msg-restore-non-pruned-header)
-           (rmail-msg-prune-header))
-         (cond (at-point-min
-                (goto-char (point-min)))
-               (on-header
-                (goto-char (point-min))
-                (search-forward "\n\n")
-                (or (re-search-backward
-                     (concat "^" (regexp-quote on-header)) nil t)
-                    (goto-char (point-min))))
-               (t
-                (save-selected-window
-                  (select-window window)
-                  (recenter old-screen-line)
-                  (if (and all-headers-visible
-                           (not (= (window-start) (point-min))))
-                      (recenter (- (window-height) 2))))))))
-      (rmail-highlight-headers))))
-
-(defun rmail-narrow-to-non-pruned-header ()
-  "Narrow to the whole (original) header of the current message."
-  (let (start end)
-    (narrow-to-region (rmail-msgbeg rmail-current-message) (point-max))
-    (goto-char (point-min))
-    (forward-line 1)
-    (if (= (following-char) ?1)
-       (progn
-         (forward-line 1)
-         (setq start (point))
-         (search-forward "*** EOOH ***\n")
-         (setq end (match-beginning 0)))
-      (forward-line 2)
-      (setq start (point))
-      (search-forward "\n\n")
-      (setq end (1- (point))))
-    (narrow-to-region start end)
-    (goto-char start)))
-
-;; Lifted from repos-count-screen-lines.
-;; Return number of screen lines between START and END.
-(defun rmail-count-screen-lines (start end)
-  (save-excursion
-    (save-restriction
-      (narrow-to-region start end)
-      (goto-char (point-min))
-      (vertical-motion (- (point-max) (point-min))))))
+(defun rmail-get-header-1 (name)
+  "Subroutine of `rmail-get-header'.
+Narrow to header, call `mail-fetch-field' to find header NAME."
+  (if (search-forward "\n\n" nil t)
+      (progn
+        (narrow-to-region (point-min) (point))
+        (mail-fetch-field name))
+    (rmail-error-bad-format)))
+
+(defun rmail-get-header (name &optional msgnum)
+  "Return the value of message header NAME, nil if it has none.
+MSGNUM specifies the message number to get it from.
+If MSGNUM is nil, use the current message."
+  (rmail-apply-in-message msgnum 'rmail-get-header-1 name))
+
+(defun rmail-set-header-1 (name value)
+  "Subroutine of `rmail-set-header'.
+Narrow to header, set header NAME to VALUE, replacing existing if present.
+VALUE nil means to remove NAME altogether."
+  (if (search-forward "\n\n" nil t)
+      (progn
+       (forward-char -1)
+       (narrow-to-region (point-min) (point))
+       (goto-char (point-min))
+       (if (re-search-forward (concat "^" (regexp-quote name) ":") nil 'move)
+            (if value
+                (progn
+                  (delete-region (point) (line-end-position))
+                  (insert " " value))
+              (delete-region (line-beginning-position)
+                             (line-beginning-position 2)))
+          (if value (insert name ": " value "\n"))))
+    (rmail-error-bad-format)))
+
+(defun rmail-set-header (name &optional msgnum value)
+  "Set message header NAME to VALUE in message number MSGNUM.
+If MSGNUM is nil, use the current message.  NAME and VALUE are strings.
+VALUE may also be nil, meaning to remove the header."
+  (rmail-apply-in-message msgnum 'rmail-set-header-1 name value)
+  (with-current-buffer rmail-buffer
+    ;; Ensure header changes get saved.
+    ;; (Note replacing a header with an identical copy modifies.)
+    (set-buffer-modified-p t)
+    ;; However: don't save in mbox format over a Babyl file
+    ;; merely because of this.
+    (rmail-dont-modify-format)))
 \f
 ;;;; *** Rmail Attributes and Keywords ***
 
-;; Make a string describing current message's attributes and keywords
-;; and set it up as the name of a minor mode
-;; so it will appear in the mode line.
+(defun rmail-get-attr-names (&optional msg)
+  "Return the message attributes in a comma separated string.
+MSG specifies the message number to get it from.
+If MSG is nil, use the current message."
+  (let ((value (rmail-get-header rmail-attribute-header msg))
+       (nmax (length rmail-attr-array))
+       result temp)
+    (when value
+      (if (> (length value) nmax)
+          (message "Warning: corrupt attribute header in message")
+        (dotimes (index (length value))
+          (setq temp (and (not (= ?- (aref value index)))
+                          (nth 1 (aref rmail-attr-array index)))
+                result
+                (cond
+                 ((and temp result) (format "%s, %s" result temp))
+                 (temp temp)
+                 (t result)))))
+      result)))
+
+(defun rmail-get-keywords (&optional msg)
+  "Return the message keywords in a comma separated string.
+MSG, if non-nil, identifies the message number to use.
+If nil, that means the current message."
+  (rmail-get-header rmail-keyword-header msg))
+
+(defun rmail-get-labels (&optional msg)
+  "Return a string with the labels (attributes and keywords) of msg MSG.
+It is put in comma-separated form.
+MSG, if non-nil, identifies the message number to use.
+If nil, that means the current message."
+  (or msg (setq msg rmail-current-message))
+  (let (attr-names keywords)
+    ;; Combine the message attributes and keywords
+    ;; into a comma-separated list.
+    (setq attr-names (rmail-get-attr-names msg)
+         keywords (rmail-get-keywords msg))
+    (if (string= keywords "")
+       (setq keywords nil))
+    (cond
+     ;; FIXME ? old rmail did not have spaces in the comma-separated lists.
+     ((and attr-names keywords) (concat " " attr-names "; " keywords))
+     (attr-names (concat " " attr-names))
+     (keywords (concat " " keywords))
+     (t ""))))
+
 (defun rmail-display-labels ()
-  (let ((blurb "") (beg (point-min-marker)) (end (point-max-marker)))
-    (save-excursion
-      (unwind-protect
-         (progn
-           (widen)
-           (goto-char (rmail-msgbeg rmail-current-message))
-           (forward-line 1)
-           (if (looking-at "[01],")
-               (progn
-                 (narrow-to-region (point) (progn (end-of-line) (point)))
-                 ;; Truly valid BABYL format requires a space before each
-                 ;; attribute or keyword name.  Put them in if missing.
-                 (let (buffer-read-only)
-                   (goto-char (point-min))
-                   (while (search-forward "," nil t)
-                     (or (looking-at "[ ,]") (eobp)
-                         (insert " "))))
-                 (goto-char (point-max))
-                 (if (search-backward ",," nil 'move)
-                     (progn
-                       (if (> (point) (1+ (point-min)))
-                           (setq blurb (buffer-substring (+ 1 (point-min)) (point))))
-                       (if (> (- (point-max) (point)) 2)
-                           (setq blurb
-                                 (concat blurb
-                                         ";"
-                                         (buffer-substring (+ (point) 3)
-                                                           (1- (point-max)))))))))))
-       ;; Note: we don't use save-restriction because that does not work right
-       ;; if changes are made outside the saved restriction
-       ;; before that restriction is restored.
-       (narrow-to-region beg end)
-       (set-marker beg nil)
-       (set-marker end nil)))
-    (while (string-match " +," blurb)
-      (setq blurb (concat (substring blurb 0 (match-beginning 0)) ","
-                         (substring blurb (match-end 0)))))
-    (while (string-match ", +" blurb)
-      (setq blurb (concat (substring blurb 0 (match-beginning 0)) ","
-                         (substring blurb (match-end 0)))))
+  "Update the current messages's attributes and keywords in mode line."
+  (let ((blurb (rmail-get-labels)))
     (setq mode-line-process
          (format " %d/%d%s"
                  rmail-current-message rmail-total-messages blurb))
@@ -2534,59 +2199,139 @@ otherwise, show it in full."
          (with-current-buffer rmail-view-buffer
            (setq mode-line-process mlp))))))
 
-;; Turn an attribute of a message on or off according to STATE.
-;; ATTR is the name of the attribute, as a string.
-;; MSGNUM is message number to change; nil means current message.
+(defun rmail-get-attr-value (attr state)
+  "Return the character value for ATTR.
+ATTR is a (numeric) index, an offset into the mbox attribute
+header value. STATE is one of nil, t, or a character value."
+  (cond
+   ((numberp state) state)
+   ((not state) ?-)
+   (t (nth 0 (aref rmail-attr-array attr)))))
+
+(defun rmail-set-attribute-1 (attr state)
+  "Subroutine of `rmail-set-attribute'.
+Set Rmail attribute ATTR to STATE in `rmail-attribute-header',
+creating the header if necessary.  Returns non-nil if a
+significant attribute change was made."
+  (let ((limit (search-forward "\n\n" nil t))
+        (value (rmail-get-attr-value attr state))
+        (inhibit-read-only t)
+        altered)
+    (goto-char (point-min))
+    (if (search-forward (concat rmail-attribute-header ": ") limit t)
+        ;; If this message already records attributes, just change the
+        ;; value for this one.
+        (let ((missing (- (+ (point) attr) (line-end-position))))
+          ;; Position point at this attribute, adding attributes if necessary.
+          (if (> missing 0)
+              (progn
+                (end-of-line)
+                (insert-char ?- missing)
+                (backward-char 1))
+            (forward-char attr))
+          ;; Change this attribute.
+          (when (/= value (char-after))
+            (setq altered t)
+            (delete-char 1)
+            (insert value)))
+      ;; Otherwise add a header line to record the attributes and set
+      ;; all but this one to no.
+      (let ((header-value "--------"))
+        (aset header-value attr value)
+        (goto-char (if limit (1- limit) (point-max)))
+        (setq altered (/= value ?-))
+        (insert rmail-attribute-header ": " header-value "\n")))
+    altered))
+
 (defun rmail-set-attribute (attr state &optional msgnum)
-  (set-buffer rmail-buffer)
-  (let ((omax (point-max-marker))
-       (omin (point-min-marker))
-       (buffer-read-only nil))
+  "Turn an attribute of a message on or off according to STATE.
+STATE is either nil or the character (numeric) value associated
+with the state (nil represents off and non-nil represents on).
+ATTR is either the index number of the attribute, or a string,
+both from `rmail-attr-array'.  MSGNUM is message number to
+change; nil means current message."
+  (let ((n 0)
+        (nmax (length rmail-attr-array)))
+    (while (and (stringp attr)
+                (< n nmax))
+      (if (string-equal attr (cadr (aref rmail-attr-array n)))
+          (setq attr n))
+      (setq n (1+ n))))
+  (if (stringp attr)
+      (error "Unknown attribute `%s'" attr))
+  ;; Ask for confirmation before setting any attribute except `unseen'
+  ;; if it would force a format change.
+  (unless (= attr rmail-unseen-attr-index)
+    (rmail-modify-format))
+  (with-current-buffer rmail-buffer
     (or msgnum (setq msgnum rmail-current-message))
-    (if (> msgnum 0)
-       (unwind-protect
-           (save-excursion
-             (widen)
-             (goto-char (+ 3 (rmail-msgbeg msgnum)))
-             (let ((curstate
-                    (not
-                     (null (search-backward (concat ", " attr ",")
-                                            (prog1 (point) (end-of-line)) t)))))
-               (or (eq curstate (not (not state)))
-                   (if curstate
-                       (delete-region (point) (1- (match-end 0)))
-                     (beginning-of-line)
-                     (forward-char 2)
-                     (insert " " attr ","))))
-             (if (string= attr "deleted")
-                 (rmail-set-message-deleted-p msgnum state)))
-         ;; Note: we don't use save-restriction because that does not work right
-         ;; if changes are made outside the saved restriction
-         ;; before that restriction is restored.
-         (narrow-to-region omin omax)
-         (set-marker omin nil)
-         (set-marker omax nil)
-         (if (= msgnum rmail-current-message)
-             (rmail-display-labels))))))
-
-;; Return t if the attributes/keywords line of msg number MSG
-;; contains a match for the regexp LABELS.
+    (when (> msgnum 0)
+      ;; The "deleted" attribute is also stored in a special vector so
+      ;; update that too.
+      (if (= attr rmail-deleted-attr-index)
+          (rmail-set-message-deleted-p msgnum state))
+      (if (prog1
+              (rmail-apply-in-message msgnum 'rmail-set-attribute-1 attr state)
+            (if (= msgnum rmail-current-message)
+                (rmail-display-labels)))
+         ;; Don't save in mbox format over a Babyl file
+         ;; merely because of a change in `unseen' attribute.
+         (if (= attr rmail-unseen-attr-index)
+             (rmail-dont-modify-format)
+           ;; Otherwise, if we modified the file text via the view buffer,
+           ;; mark the main buffer modified too.
+           (set-buffer-modified-p t))))))
+
+(defun rmail-message-attr-p (msg attrs)
+  "Return non-nil if message number MSG has attributes matching regexp ATTRS."
+  (let ((value (rmail-get-header rmail-attribute-header msg)))
+    (and value (string-match attrs value))))
+
+(defun rmail-message-unseen-p (msgnum)
+  "Return non-nil if message number MSGNUM has the unseen attribute."
+  (rmail-message-attr-p msgnum "......U"))
+
+;; FIXME rmail-get-labels does some formatting (eg leading space, `;'
+;; between attributes and labels), so this might not do what you want.
+;; Eg see rmail-sort-by-labels.  rmail-get-labels could have an
+;; optional `noformat' argument.
 (defun rmail-message-labels-p (msg labels)
-  (save-excursion
-    (save-restriction
-      (widen)
-      (goto-char (rmail-msgbeg msg))
-      (forward-char 3)
-      (re-search-backward labels (prog1 (point) (end-of-line)) t))))
+  "Return non-nil if message number MSG has labels matching regexp LABELS."
+  (string-match labels (rmail-get-labels msg)))
 \f
 ;;;; *** Rmail Message Selection And Support ***
 
 (defun rmail-msgend (n)
+  "Return the start position for message number N."
   (marker-position (aref rmail-message-vector (1+ n))))
 
 (defun rmail-msgbeg (n)
+  "Return the end position for message number N."
   (marker-position (aref rmail-message-vector n)))
 
+(defun rmail-apply-in-message (msgnum function &rest args)
+  "Call FUNCTION on ARGS while narrowed to message MSGNUM.
+Point is at the start of the message.
+This returns what the call to FUNCTION returns.
+If MSGNUM is nil, use the current message."
+  (with-current-buffer rmail-buffer
+    (or msgnum (setq msgnum rmail-current-message))
+    (when (> msgnum 0)
+      (let (msgbeg msgend)
+       (setq msgbeg (rmail-msgbeg msgnum))
+       (setq msgend (rmail-msgend msgnum))
+       ;; All access to the rmail-buffer's local variables is now finished...
+       (save-excursion
+         ;; ... so it is ok to go to a different buffer.
+         (if (rmail-buffers-swapped-p) (set-buffer rmail-view-buffer))
+         (save-excursion
+           (save-restriction
+             (widen)
+             (goto-char msgbeg)
+             (narrow-to-region msgbeg msgend)
+             (apply function args))))))))
+
+;; Unused (save for commented out code in rmailedit.el).
 (defun rmail-widen-to-current-msgbeg (function)
   "Call FUNCTION with point at start of internal data of current message.
 Assumes that bounds were previously narrowed to display the message in Rmail.
@@ -2607,16 +2352,17 @@ change the invisible header text."
        ;; before that restriction is restored.
       (narrow-to-region (rmail-msgbeg rmail-current-message)
                        (rmail-msgend rmail-current-message)))))
+\f
+;; Manage the message vectors and counters.
 
 (defun rmail-forget-messages ()
   (unwind-protect
       (if (vectorp rmail-message-vector)
-         (let* ((i 0)
-                (v rmail-message-vector)
+         (let* ((v rmail-message-vector)
                 (n (length v)))
-           (while (< i n)
-             (move-marker (aref v i)  nil)
-             (setq i (1+ i)))))
+           (dotimes (i n)
+             (if (aref v i)
+                 (move-marker (aref v i)  nil)))))
     (setq rmail-message-vector nil)
     (setq rmail-msgref-vector nil)
     (setq rmail-deleted-vector nil)))
@@ -2629,6 +2375,9 @@ change the invisible header text."
       (rmail-set-message-counters)))
 
 (defun rmail-count-new-messages (&optional nomsg)
+  "Count the number of new messages.
+The buffer should be narrowed to include only the new messages.
+Output a helpful message unless NOMSG is non-nil."
   (let* ((case-fold-search nil)
         (total-messages 0)
         (messages-head nil)
@@ -2638,8 +2387,6 @@ change the invisible header text."
     ;; Put at the end of messages-head
     ;; the entry for message N+1, which marks
     ;; the end of message N.  (N = number of messages).
-    (search-backward "\n\^_")
-    (forward-char 1)
     (setq messages-head (list (point-marker)))
     (rmail-set-message-counters-counter (point-min))
     (setq rmail-current-message (1+ rmail-total-messages))
@@ -2674,83 +2421,137 @@ change the invisible header text."
             (case-fold-search nil)
             (messages-head nil)
             (deleted-head nil))
+       ;; Determine how many messages follow point.
        (message "Counting messages...")
        (goto-char (point-max))
        ;; Put at the end of messages-head
        ;; the entry for message N+1, which marks
        ;; the end of message N.  (N = number of messages).
-       (search-backward "\n\^_" nil t)
-       (if (/= (point) (point-max)) (forward-char 1))
        (setq messages-head (list (point-marker)))
-       (rmail-set-message-counters-counter (min (point) point-save))
-       (setq messages-after-point total-messages)
-       (rmail-set-message-counters-counter)
+       (setq messages-after-point 
+             (or (rmail-set-message-counters-counter (min (point) point-save))
+                 0))
+
        (setq rmail-total-messages total-messages)
        (setq rmail-current-message
              (min total-messages
                   (max 1 (- total-messages messages-after-point))))
-       (setq rmail-message-vector
-             (apply 'vector (cons (point-min-marker) messages-head))
-             rmail-deleted-vector (concat "0" deleted-head)
-             rmail-summary-vector (make-vector rmail-total-messages nil)
+
+       ;; Make an element 0 in rmail-message-vector and rmail-deleted-vector
+       ;; which will never be used.
+       (push nil messages-head)
+       (push ?0 deleted-head)
+       (setq rmail-message-vector (apply 'vector messages-head)
+             rmail-deleted-vector (concat deleted-head))
+
+       (setq rmail-summary-vector (make-vector rmail-total-messages nil)
              rmail-msgref-vector (make-vector (1+ rmail-total-messages) nil))
+
        (let ((i 0))
          (while (<= i rmail-total-messages)
            (aset rmail-msgref-vector i (list i))
            (setq i (1+ i))))
+       (let ((i 0))
+         (while (<= i rmail-total-messages)
+           (rmail-set-message-deleted-p i (rmail-message-attr-p i ".D"))
+           (setq i (1+ i))))
        (message "Counting messages...done")))))
 
-(defun rmail-set-message-counters-counter (&optional stop)
+
+(defsubst rmail-collect-deleted (message-end)
+  "Collect the message deletion flags for each message.
+MESSAGE-END is the buffer position corresponding to the end of
+the message.  Point is at the beginning of the message."
+  ;; NOTE: This piece of code will be executed on a per-message basis.
+  ;; In the face of thousands of messages, it has to be as fast as
+  ;; possible, hence some brute force constant use is employed in
+  ;; addition to inlining.
+  (save-excursion
+    (setq deleted-head
+         (cons (if (and (search-forward (concat rmail-attribute-header ": ") message-end t)
+                        (looking-at "?D"))
+                   ?D
+                 ?\s) deleted-head))))
+
+(defun rmail-set-message-counters-counter (&optional spot-to-find)
+  "Collect the start positions of messages in list `messages-head'.
+Return the number of messages after the one containing SPOT-TO-FIND."
   (let ((start (point))
-       next)
-    (while (search-backward "\n\^_\^L" stop t)
-      ;; Detect messages that have been added with DOS line endings and
-      ;; convert the line endings for such messages.
-      (setq next (point))
-      (if (looking-at "\n\^_\^L\r\n")
-         (let ((buffer-read-only nil)
-               (buffer-undo t))
-           (message "Counting messages...(converting line endings)")
-           (save-excursion
-             (goto-char start)
-             (while (search-backward "\r\n" next t)
-               (delete-char 1)))))
-      (setq start next)
-      (forward-char 1)
-      (setq messages-head (cons (point-marker) messages-head))
-      (save-excursion
-       (setq deleted-head
-             (cons (if (search-backward ", deleted,"
-                                        (prog1 (point)
-                                          (forward-line 2))
-                                        t)
-                       ?D ?\ )
-                   deleted-head)))
-      (if (zerop (% (setq total-messages (1+ total-messages)) 20))
-         (message "Counting messages...%d" total-messages)))))
+       messages-after-spot)
+    (while (search-backward "\n\nFrom " nil t)
+      (forward-char 2)
+      (when (looking-at rmail-unix-mail-delimiter)
+       (if (and (<= (point) spot-to-find)
+                (null messages-after-spot))
+           (setq messages-after-spot total-messages))
+       (rmail-collect-deleted start)
+       (setq messages-head (cons (point-marker) messages-head)
+             total-messages (1+ total-messages)
+             start (point))
+       ;; Show progress after every 20 messages or so.
+       (if (zerop (% total-messages 20))
+           (message "Counting messages...%d" total-messages))))
+    ;; Handle the first message, maybe.
+    (goto-char (point-min))
+    (unless (not (looking-at rmail-unix-mail-delimiter))
+      (if (and (<= (point) spot-to-find)
+              (null messages-after-spot))
+         (setq messages-after-spot total-messages))
+      (rmail-collect-deleted start)
+      (setq messages-head (cons (point-marker) messages-head)
+           total-messages (1+ total-messages)))
+    messages-after-spot))
+\f
+;; Display a message.
+
+;;;; *** Rmail Message Formatting and Header Manipulation ***
+
+;; This is used outside of rmail.
+(defun rmail-msg-is-pruned ()
+  "Return nil if the current message is showing full headers."
+  (with-current-buffer (if (rmail-buffers-swapped-p) rmail-view-buffer
+                         rmail-buffer)
+    (eq rmail-header-style 'normal)))
+
+(defun rmail-toggle-header (&optional arg)
+  "Toggle between showing full and normal message headers.
+With optional integer ARG, show the normal message header if ARG
+is greater than zero; otherwise, show it in full."
+  (interactive "P")
+  (let ((rmail-header-style
+        (if (numberp arg)
+            (if (> arg 0) 'normal 'full)
+           (if (rmail-msg-is-pruned) 'full 'normal))))
+    (rmail-show-message)))
 
 (defun rmail-beginning-of-message ()
   "Show current message starting from the beginning."
   (interactive)
-  (let ((rmail-show-message-hook
-        (list (function (lambda ()
-                          (goto-char (point-min)))))))
+  (let ((rmail-show-message-hook '((lambda () (goto-char (point-min)))))
+       (rmail-header-style (with-current-buffer (if (rmail-buffers-swapped-p)
+                                                    rmail-view-buffer
+                                                  rmail-buffer)
+                             rmail-header-style)))
     (rmail-show-message rmail-current-message)))
 
 (defun rmail-end-of-message ()
   "Show bottom of current message."
   (interactive)
-  (let ((rmail-show-message-hook
-        (list (function (lambda ()
-                          (goto-char (point-max))
-                          (recenter (1- (window-height))))))))
+  (let ((rmail-show-message-hook '((lambda ()
+                                    (goto-char (point-max))
+                                    (recenter (1- (window-height))))))
+       (rmail-header-style (with-current-buffer (if (rmail-buffers-swapped-p)
+                                                    rmail-view-buffer
+                                                  rmail-buffer)
+                             rmail-header-style)))
     (rmail-show-message rmail-current-message)))
 
 (defun rmail-unknown-mail-followup-to ()
   "Handle a \"Mail-Followup-To\" header field with an unknown mailing list.
 Ask the user whether to add that list name to `mail-mailing-lists'."
+  ;; FIXME s-r not needed?  Use rmail-get-header?
+  ;; We have not narrowed to the headers at ths point?
    (save-restriction
-     (rmail-narrow-to-non-pruned-header)
      (let ((mail-followup-to (mail-fetch-field "mail-followup-to" nil t)))
        (when mail-followup-to
         (let ((addresses
@@ -2779,209 +2580,294 @@ Ask the user whether to add that list name to `mail-mailing-lists'."
               (customize-save-variable 'mail-mailing-lists
                                        (cons addr mail-mailing-lists)))))))))
 
+(defun rmail-widen ()
+  "Display the entire mailbox file."
+  (interactive)
+  (rmail-swap-buffers-maybe)
+  (widen))
+\f
+(defun rmail-no-mail-p ()
+  "Return nil if there is mail, else \"No mail.\"."
+  (if (zerop rmail-total-messages)
+      (save-excursion
+       (with-current-buffer rmail-view-buffer
+         (erase-buffer)
+         "No mail."))))
+
 (defun rmail-show-message (&optional n no-summary)
   "Show message number N (prefix argument), counting from start of file.
-If summary buffer is currently displayed, update current message there also."
+If summary buffer is currently displayed, update current message there also.
+N defaults to the current message."
   (interactive "p")
   (or (eq major-mode 'rmail-mode)
       (switch-to-buffer rmail-buffer))
+  ;; FIXME: Why do we swap the raw data back in?
+  (rmail-swap-buffers-maybe)
   (rmail-maybe-set-message-counters)
   (widen)
-  (if (zerop rmail-total-messages)
-      (progn (narrow-to-region (point-min) (1- (point-max)))
-            (goto-char (point-min))
-            (setq mode-line-process nil))
-    (let (blurb coding-system)
-      (if (not n)
-         (setq n rmail-current-message)
-       (cond ((<= n 0)
-              (setq n 1
-                    rmail-current-message 1
-                    blurb "No previous message"))
-             ((> n rmail-total-messages)
-              (setq n rmail-total-messages
-                    rmail-current-message rmail-total-messages
-                    blurb "No following message"))
-             (t
-              (setq rmail-current-message n))))
-      (let ((beg (rmail-msgbeg n)))
+  (let ((blurb (rmail-show-message-1 n)))
+    (or (zerop rmail-total-messages)
+       (progn
+         (when mail-mailing-lists
+           (rmail-unknown-mail-followup-to))
+         (if transient-mark-mode (deactivate-mark))
+         ;; If there is a summary buffer, try to move to this message
+         ;; in that buffer.  But don't complain if this message is
+         ;; not mentioned in the summary.  Don't do this at all if we
+         ;; were called on behalf of cursor motion in the summary
+         ;; buffer.
+         (and (rmail-summary-exists) (not no-summary)
+              (let ((curr-msg rmail-current-message))
+                (rmail-select-summary
+                 (rmail-summary-goto-msg curr-msg t t))))
+         (with-current-buffer rmail-buffer
+           (rmail-auto-file))))
+    (if blurb
+       (message blurb))))
+
+(defun rmail-is-text-p ()
+  "Return t if the region contains a text message, nil otherwise."
+  (save-excursion
+    (let ((text-regexp "\\(text\\|message\\)/")
+         (content-type-header (mail-fetch-field "content-type")))
+      ;; The message is text if either there is no content type header
+      ;; (a default of "text/plain; charset=US-ASCII" is assumed) or
+      ;; the base content type is either text or message.
+      (or (not content-type-header)
+         (string-match text-regexp content-type-header)))))
+
+(defcustom rmail-show-message-verbose-min 200000
+  "Message size at which to show progress messages for displaying it."
+  :type 'integer
+  :group 'rmail
+  :version "23.1")
+
+(defun rmail-show-message-1 (&optional msg)
+  "Show message MSG (default: current message) using `rmail-view-buffer'.
+Return text to display in the minibuffer if MSG is out of
+range (displaying a reasonable choice as well), nil otherwise.
+The current mail message becomes the message displayed."
+  (let ((mbox-buf rmail-buffer)
+       (view-buf rmail-view-buffer)
+       blurb beg end body-start coding-system character-coding
+       is-text-message header-style)
+    (if (not msg)
+       (setq msg rmail-current-message))
+    (unless (setq blurb (rmail-no-mail-p))
+      (cond ((<= msg 0)
+            (setq msg 1
+                  rmail-current-message 1
+                  blurb "No previous message"))
+           ((> msg rmail-total-messages)
+            (setq msg rmail-total-messages
+                  rmail-current-message rmail-total-messages
+                  blurb "No following message"))
+           (t (setq rmail-current-message msg)))
+      (with-current-buffer rmail-buffer
+       (setq header-style rmail-header-style)
+       ;; Mark the message as seen
+       (rmail-set-attribute rmail-unseen-attr-index nil)
+       ;; bracket the message in the mail
+       ;; buffer and determine the coding system the transfer encoding.
+       (rmail-swap-buffers-maybe)
+       (setq beg (rmail-msgbeg msg)
+             end (rmail-msgend msg))
+       (when (> (- end beg) rmail-show-message-verbose-min)
+         (message "Showing message %d" msg))
+       (narrow-to-region beg end)
+       (goto-char beg)
+       (setq body-start (search-forward "\n\n" nil t))
+       (narrow-to-region beg (point))
        (goto-char beg)
-       (forward-line 1)
        (save-excursion
-         (let ((end (rmail-msgend n)))
-           (save-restriction
-             (if (prog1 (= (following-char) ?0)
-                   (forward-line 2)
-                   ;; If there's a Summary-line in the (otherwise empty)
-                   ;; header, we didn't yet get past the EOOH line.
-                   (if (looking-at "^\\*\\*\\* EOOH \\*\\*\\*\n")
-                       (forward-line 1))
-                   (narrow-to-region (point) end))
-                 (rfc822-goto-eoh)
-               (search-forward "\n*** EOOH ***\n" end t))
-             (narrow-to-region beg (point))
-             (goto-char (point-min))
-             (if (re-search-forward "^X-Coding-System: *\\(.*\\)$" nil t)
-                 (let ((coding-system (intern (match-string 1))))
-                   (condition-case nil
-                       (progn
-                         (check-coding-system coding-system)
-                         (setq buffer-file-coding-system coding-system))
-                     (error
-                      (setq buffer-file-coding-system nil))))
-               (setq buffer-file-coding-system nil)))))
-       ;; Clear the "unseen" attribute when we show a message.
-       (rmail-set-attribute "unseen" nil)
-       (let ((end (rmail-msgend n)))
-         ;; Reformat the header, or else find the reformatted header.
-         (if (= (following-char) ?0)
-             (rmail-reformat-message beg end)
-           (search-forward "\n*** EOOH ***\n" end t)
-           (narrow-to-region (point) end)))
-       (goto-char (point-min))
-       (walk-windows
-        (function (lambda (window)
-                    (if (eq (window-buffer window) (current-buffer))
-                        (set-window-point window (point)))))
-        nil t)
+         (if (re-search-forward "^X-Coding-System: *\\(.*\\)$" nil t)
+             (setq coding-system (intern (match-string 1)))
+           (setq coding-system (rmail-get-coding-system))))
+       (setq character-coding (mail-fetch-field "content-transfer-encoding")
+             is-text-message (rmail-is-text-p))
+       (if character-coding
+           (setq character-coding (downcase character-coding)))
+       (narrow-to-region beg end)
+       ;; Decode the message body into an empty view buffer using a
+       ;; unibyte temporary buffer where the character decoding takes
+       ;; place.
+       (with-current-buffer rmail-view-buffer
+         ;; We give the view buffer a buffer-local value of
+         ;; rmail-header-style based on the binding in effect when
+         ;; this function is called; `rmail-toggle-headers' can
+         ;; inspect this value to determine how to toggle.
+         (set (make-local-variable 'rmail-header-style) header-style)
+         (erase-buffer))
+       (if (null character-coding)
+           ;; Do it directly since that is fast.
+           (rmail-decode-region body-start end coding-system view-buf)
+         ;; Can this be done directly, skipping the temp buffer?
+         (with-temp-buffer
+           (set-buffer-multibyte nil)
+           (insert-buffer-substring mbox-buf body-start end)
+           (cond
+            ((string= character-coding "quoted-printable")
+             (mail-unquote-printable-region (point-min) (point-max)))
+            ((and (string= character-coding "base64") is-text-message)
+             (base64-decode-region (point-min) (point-max)))
+            ((eq character-coding 'uuencode)
+             (error "uuencoded messages are not supported yet"))
+            (t))
+           (rmail-decode-region (point-min) (point-max)
+                                coding-system view-buf)))
+       (with-current-buffer rmail-view-buffer
+         ;; Unquote quoted From lines
+         (goto-char (point-min))
+         (while (re-search-forward "^>+From " nil t)
+           (beginning-of-line)
+           (delete-char 1)
+           (forward-line))
+         (goto-char (point-min)))
+       ;; Copy the headers to the front of the message view buffer.
+       (rmail-copy-headers beg end)
+       ;; Add the separator (blank line) between headers and body;
+       ;; highlight the message, activate any URL like text and add
+       ;; special highlighting for and quoted material.
+       (with-current-buffer rmail-view-buffer
+         (insert "\n")
+         (goto-char (point-min))
+         (rmail-highlight-headers)
+                                       ;(rmail-activate-urls)
+                                       ;(rmail-process-quoted-material)
+         )
+       ;; Update the mode-line with message status information and swap
+       ;; the view buffer/mail buffer contents.
        (rmail-display-labels)
-       (if (eq rmail-enable-mime t)
-           (funcall rmail-show-mime-function)
-         (setq rmail-view-buffer rmail-buffer))
-       (when mail-mailing-lists
-         (rmail-unknown-mail-followup-to))
-       (rmail-highlight-headers)
-       (if transient-mark-mode (deactivate-mark))
+       (rmail-swap-buffers)
+       (setq rmail-buffer-swapped t)
        (run-hooks 'rmail-show-message-hook)
-       ;; If there is a summary buffer, try to move to this message
-       ;; in that buffer.  But don't complain if this message
-       ;; is not mentioned in the summary.
-       ;; Don't do this at all if we were called on behalf
-       ;; of cursor motion in the summary buffer.
-       (and (rmail-summary-exists) (not no-summary)
-            (let ((curr-msg rmail-current-message))
-              (rmail-select-summary
-               (rmail-summary-goto-msg curr-msg t t))))
-       (with-current-buffer rmail-buffer
-         (rmail-auto-file))
-       (if blurb
-           (message blurb))))))
-
-(defun rmail-redecode-body (coding &optional raw)
+       (when (> (- end beg) rmail-show-message-verbose-min)
+         (message "Showing message %d...done" msg))))
+    blurb))
+
+(defun rmail-copy-headers (beg end &optional ignored-headers)
+  "Copy displayed header fields to the message viewer buffer.
+BEG and END marks the start and end positions of the message in
+the mbox buffer.  If the optional argument IGNORED-HEADERS is
+non-nil, ignore all header fields whose names match that regexp.
+Otherwise, if `rmail-displayed-headers' is non-nil, copy only
+those header fields whose names match that regexp.  Otherwise,
+copy all header fields whose names do not match
+`rmail-ignored-headers' (unless they also match
+`rmail-nonignored-headers').  Moves point in the message viewer
+buffer to the end of the headers."
+  (let ((header-start-regexp "\n[^ \t]")
+       lim)
+    (with-current-buffer rmail-buffer
+      (when (search-forward "\n\n" nil t)
+       (forward-char -1)
+       (save-restriction
+         ;; Put point right after the From header line.
+         (narrow-to-region beg (point))
+         (goto-char (point-min))
+         (unless (re-search-forward header-start-regexp nil t)
+           (rmail-error-bad-format))
+         (forward-char -1)
+         (cond
+          ;; Handle the case where all headers should be copied.
+          ((eq rmail-header-style 'full)
+           (prepend-to-buffer rmail-view-buffer beg (point-max))
+           ;; rmail-show-message-1 expects this function to leave point
+           ;; at the end of the headers.
+
+           (let ((len (- (point-max) beg)))
+             (with-current-buffer rmail-view-buffer
+               (goto-char (1+ len)))))
+
+          ;; Handle the case where the headers matching the displayed
+          ;; headers regexp should be copied.
+          ((and rmail-displayed-headers (null ignored-headers))
+           (while (not (eobp))
+             (save-excursion
+               (setq lim (if (re-search-forward header-start-regexp nil t)
+                             (1+ (match-beginning 0))
+                           (point-max))))
+             (when (looking-at rmail-displayed-headers)
+               (append-to-buffer rmail-view-buffer (point) lim))
+             (goto-char lim)))
+          ;; Handle the ignored headers.
+          ((or ignored-headers (setq ignored-headers rmail-ignored-headers))
+           (while (and ignored-headers (not (eobp)))
+             (save-excursion
+               (setq lim (if (re-search-forward header-start-regexp nil t)
+                             (1+ (match-beginning 0))
+                           (point-max))))
+             (if (and (looking-at ignored-headers)
+                      (not (looking-at rmail-nonignored-headers)))
+                 (goto-char lim)
+               (append-to-buffer rmail-view-buffer (point) lim)
+               (goto-char lim))))
+          (t (error "No headers selected for display!"))))))))
+
+(defun rmail-redecode-body (coding)
   "Decode the body of the current message using coding system CODING.
 This is useful with mail messages that have malformed or missing
 charset= headers.
 
 This function assumes that the current message is already decoded
 and displayed in the RMAIL buffer, but the coding system used to
-decode it was incorrect.  It then encodes the message back to its
-original form, and decodes it again, using the coding system CODING.
-
-Optional argument RAW, if non-nil, means don't encode the message
-before decoding it with the new CODING.  This is useful if the current
-message text was produced by some function which invokes `insert',
-since `insert' leaves unibyte character codes 128 through 255 unconverted
-to multibyte.  One example of such a situation is when the text was
-produced by `base64-decode-region'.
-
-Interactively, invoke the function with a prefix argument to set RAW
-non-nil.
-
-Note that if Emacs erroneously auto-detected one of the iso-2022
-encodings in the message, this function might fail because the escape
-sequences that switch between character sets and also single-shift and
-locking-shift codes are impossible to recover.  This function is meant
-to be used to fix messages encoded with 8-bit encodings, such as
-iso-8859, koi8-r, etc."
+decode it was incorrect.  It then decodes the message again,
+using the coding system CODING."
   (interactive "zCoding system for re-decoding this message: ")
   (when (not rmail-enable-mime)
-    (or (eq major-mode 'rmail-mode)
-       (switch-to-buffer rmail-buffer))
-    (save-excursion
-      (let ((pruned (rmail-msg-is-pruned))
-           (raw (or raw current-prefix-arg)))
-       (unwind-protect
-           (let ((msgbeg (rmail-msgbeg rmail-current-message))
-                 (msgend (rmail-msgend rmail-current-message))
-                 x-coding-header)
-             ;; We need the message headers pruned (we later restore
-             ;; the pruned stat to what it was, see the end of
-             ;; unwind-protect form).
-             (or pruned
-                 (rmail-toggle-header 1))
-             (narrow-to-region msgbeg msgend)
-             (goto-char (point-min))
-             (when (search-forward "\n*** EOOH ***\n" (point-max) t)
-               (narrow-to-region msgbeg (point)))
-             (goto-char (point-min))
-             (if (re-search-forward "^X-Coding-System: *\\(.*\\)$" nil t)
-                 (let ((old-coding (intern (match-string 1)))
-                       (buffer-read-only nil))
-                   (check-coding-system old-coding)
-                   ;; Make sure the new coding system uses the same EOL
-                   ;; conversion, to prevent ^M characters from popping
-                   ;; up all over the place.
-                   (setq coding
-                         (coding-system-change-eol-conversion
-                          coding
-                          (coding-system-eol-type old-coding)))
-                   ;; If old-coding is `undecided', encode-coding-region
-                   ;; will not encode the text at all.  Find a proper
-                   ;; non-trivial encoding to use.
-                   (if (memq (coding-system-base old-coding) '(nil undecided))
-                       (setq old-coding
-                             (car (find-coding-systems-region msgbeg msgend))))
-                   (setq x-coding-header (point-marker))
-                   (narrow-to-region msgbeg msgend)
-                   (and (null raw)
-                        ;; If old and new encoding are the same, it
-                        ;; clearly doesn't make sense to encode.
-                        (not (coding-system-equal
-                              (coding-system-base old-coding)
-                              (coding-system-base coding)))
-                        ;; If the body includes only eight-bit-*
-                        ;; characters, encoding might fail, e.g. with
-                        ;; UTF-8, and isn't needed anyway.
-                        (> (length (delq 'ascii
-                                         (delq 'eight-bit-graphic
-                                               (delq 'eight-bit-control
-                                                     (find-charset-region
-                                                      msgbeg msgend)))))
-                           0)
-                        (encode-coding-region (point) msgend old-coding))
-                   (decode-coding-region (point) msgend coding)
-                   (setq last-coding-system-used coding)
-                   ;; Rewrite the coding-system header according
-                   ;; to what we did.
-                   (goto-char x-coding-header)
-                   (delete-region (point)
-                                  (save-excursion
-                                    (beginning-of-line)
-                                    (point)))
-                   (insert "X-Coding-System: "
-                           (symbol-name last-coding-system-used))
-                   (set-marker x-coding-header nil)
-                   (rmail-show-message))
-               (error "No X-Coding-System header found")))
-         (or pruned
-             (rmail-toggle-header 0)))))))
-
-;; Find all occurrences of certain fields, and highlight them.
+    (with-current-buffer rmail-buffer
+      (rmail-swap-buffers-maybe)
+      (save-restriction
+       (widen)
+       (let ((msgbeg (rmail-msgbeg rmail-current-message))
+             (msgend (rmail-msgend rmail-current-message))
+             (buffer-read-only nil)
+             body-start x-coding-header old-coding)
+         (narrow-to-region msgbeg msgend)
+         (goto-char (point-min))
+         (unless (setq body-start (search-forward "\n\n" (point-max) 1))
+           (error "No message body"))
+
+         (save-restriction
+           ;; Narrow to headers
+           (narrow-to-region (point-min) body-start)
+           (setq x-coding-header (goto-char (point-min)))
+           (if (not (re-search-forward "^X-Coding-System: *\\(.*\\)$" nil t))
+               (setq old-coding (rmail-get-coding-system))
+             (setq old-coding (intern (match-string 1)))
+             (setq x-coding-header (point)))
+           (check-coding-system old-coding)
+           ;; Make sure the new coding system uses the same EOL
+           ;; conversion, to prevent ^M characters from popping up
+           ;; all over the place.
+           (let ((eol-type (coding-system-eol-type old-coding)))
+             (if (numberp eol-type)
+                 (setq coding
+                       (coding-system-change-eol-conversion coding eol-type))))
+           (when (not (coding-system-equal
+                       (coding-system-base old-coding)
+                       (coding-system-base coding)))
+             ;; Rewrite the coding-system header.
+             (goto-char x-coding-header)
+             (if (> (point) (point-min))
+                 (delete-region (line-beginning-position) (point))
+               (forward-line)
+               (insert "\n")
+               (forward-line -1))
+             (insert "X-Coding-System: "
+                     (symbol-name coding))))
+         (rmail-show-message))))))
+
 (defun rmail-highlight-headers ()
-  ;; Do this only if the system supports faces.
-  (if (and (fboundp 'internal-find-face)
-          rmail-highlighted-headers)
+  "Highlight the headers specified by `rmail-highlighted-headers'.
+Uses the face `rmail-highlight'."
+  (if rmail-highlighted-headers
       (save-excursion
        (search-forward "\n\n" nil 'move)
        (save-restriction
          (narrow-to-region (point-min) (point))
          (let ((case-fold-search t)
                (inhibit-read-only t)
-               ;; Highlight with boldface if that is available.
-               ;; Otherwise use the `highlight' face.
-               (face (or 'rmail-highlight
-                         (if (face-differs-from-default-p 'bold)
-                             'bold 'highlight)))
                ;; List of overlays to reuse.
                (overlays rmail-overlay-list))
            (goto-char (point-min))
@@ -3000,22 +2886,24 @@ iso-8859, koi8-r, etc."
                    (progn
                      (setq overlay (car overlays)
                            overlays (cdr overlays))
-                     (overlay-put overlay 'face face)
+                     (overlay-put overlay 'face 'rmail-highlight)
                      (move-overlay overlay beg (point)))
                  ;; Make a new overlay and add it to
                  ;; rmail-overlay-list.
                  (setq overlay (make-overlay beg (point)))
-                 (overlay-put overlay 'face face)
+                 (overlay-put overlay 'face 'rmail-highlight)
                  (setq rmail-overlay-list
                        (cons overlay rmail-overlay-list))))))))))
 
 (defun rmail-auto-file ()
   "Automatically move a message into a sub-folder based on criteria.
 Called when a new message is displayed."
-  (if (or (rmail-message-labels-p rmail-current-message "filed")
+  (if (or (zerop rmail-total-messages)
+         (rmail-message-attr-p rmail-current-message "...F")
          (not (string= (buffer-file-name)
                        (expand-file-name rmail-file-name))))
-      ;; Do nothing if it's already been filed.
+      ;; Do nothing if the message has already been filed or if there
+      ;; are no messages.
       nil
     ;; Find out some basics (common fields)
     (let ((from (mail-fetch-field "from"))
@@ -3041,9 +2929,11 @@ Called when a new message is displayed."
                (rmail-delete-forward)
              (if (string= "/dev/null" folder)
                  (rmail-delete-message)
-               (rmail-output-to-rmail-file folder 1 t)
+               (rmail-output folder 1)
                (setq d nil))))
        (setq d (cdr d))))))
+\f
+;; Simple message motion commands.
 
 (defun rmail-next-message (n)
   "Show following message whether deleted or not.
@@ -3107,59 +2997,32 @@ or forward if N is negative."
   (rmail-show-message rmail-total-messages))
 
 (defun rmail-what-message ()
-  (let ((where (point))
-       (low 1)
-       (high rmail-total-messages)
-       (mid (/ rmail-total-messages 2)))
+  "For debugging Rmail: find the message number that point is in."
+  (let* ((high rmail-total-messages)
+         (mid (/ high 2))
+         (low 1)
+         (where (with-current-buffer (if (rmail-buffers-swapped-p)
+                                         rmail-view-buffer
+                                       (current-buffer))
+                  (point))))
     (while (> (- high low) 1)
       (if (>= where (rmail-msgbeg mid))
-         (setq low mid)
-       (setq high mid))
+          (setq low mid)
+          (setq high mid))
       (setq mid (+ low (/ (- high low) 2))))
     (if (>= where (rmail-msgbeg high)) high low)))
-
-(defun rmail-message-recipients-p (msg recipients &optional primary-only)
-  (save-restriction
-    (goto-char (rmail-msgbeg msg))
-    (search-forward "\n*** EOOH ***\n")
-    (narrow-to-region (point) (progn (search-forward "\n\n") (point)))
-    (or (string-match recipients (or (mail-fetch-field "To") ""))
-       (string-match recipients (or (mail-fetch-field "From") ""))
-       (if (not primary-only)
-           (string-match recipients (or (mail-fetch-field "Cc") ""))))))
-
-(defun rmail-message-regexp-p (n regexp)
-  "Return t, if for message number N, regexp REGEXP matches in the header."
-  (let ((beg (rmail-msgbeg n))
-       (end (rmail-msgend n)))
-    (goto-char beg)
-    (forward-line 1)
-    (save-excursion
-      (save-restriction
-       (if (prog1 (= (following-char) ?0)
-             (forward-line 2)
-             ;; If there's a Summary-line in the (otherwise empty)
-             ;; header, we didn't yet get past the EOOH line.
-             (when (looking-at "^\\*\\*\\* EOOH \\*\\*\\*\n")
-               (forward-line 1))
-             (setq beg (point))
-             (narrow-to-region (point) end))
-           (progn
-             (rfc822-goto-eoh)
-             (setq end (point)))
-         (setq beg (point))
-         (search-forward "\n*** EOOH ***\n" end t)
-         (setq end (1+ (match-beginning 0)))))
-       (goto-char beg)
-       (if rmail-enable-mime
-           (funcall rmail-search-mime-header-function n regexp end)
-         (re-search-forward regexp end t)))))
+\f
+;; Searching in Rmail file.
 
 (defun rmail-search-message (msg regexp)
   "Return non-nil, if for message number MSG, regexp REGEXP matches."
+  ;; This is adequate because its only caller, rmail-search,
+  ;; unswaps the buffers.
   (goto-char (rmail-msgbeg msg))
   (if rmail-enable-mime
-      (funcall rmail-search-mime-message-function msg regexp)
+      (if rmail-search-mime-message-function
+          (funcall rmail-search-mime-message-function msg regexp)
+        (error "You must set `rmail-search-mime-message-function'"))
     (re-search-forward regexp (rmail-msgend msg) t)))
 
 (defvar rmail-search-last-regexp nil)
@@ -3191,28 +3054,27 @@ Interactively, empty argument means use same regexp used last time."
           (if (< n 0) "Reverse " "")
           regexp)
   (set-buffer rmail-buffer)
-  (rmail-maybe-set-message-counters)
-  (let ((omin (point-min))
-       (omax (point-max))
-       (opoint (point))
-       win
+  (let ((orig-message rmail-current-message)
+       (msg rmail-current-message)
        (reversep (< n 0))
-       (msg rmail-current-message))
+       (opoint (if (rmail-buffers-swapped-p) (point)))
+       found)
+    (rmail-swap-buffers-maybe)
+    (rmail-maybe-set-message-counters)
+    (widen)
     (unwind-protect
-       (progn
-         (widen)
-         (while (/= n 0)
-           ;; Check messages one by one, advancing message number up or down
-           ;; but searching forward through each message.
-           (if reversep
-               (while (and (null win) (> msg 1))
-                 (setq msg (1- msg)
-                       win (rmail-search-message msg regexp)))
-             (while (and (null win) (< msg rmail-total-messages))
-               (setq msg (1+ msg)
-                     win (rmail-search-message msg regexp))))
-           (setq n (+ n (if reversep 1 -1)))))
-      (if win
+       (while (/= n 0)
+         ;; Check messages one by one, advancing message number up or
+         ;; down but searching forward through each message.
+         (if reversep
+             (while (and (null found) (> msg 1))
+               (setq msg (1- msg)
+                     found (rmail-search-message msg regexp)))
+           (while (and (null found) (< msg rmail-total-messages))
+             (setq msg (1+ msg)
+                   found (rmail-search-message msg regexp))))
+         (setq n (+ n (if reversep 1 -1))))
+      (if found
          (progn
            (rmail-show-message msg)
            ;; Search forward (if this is a normal search) or backward
@@ -3230,8 +3092,8 @@ Interactively, empty argument means use same regexp used last time."
            (message "%sRmail search for %s...done"
                     (if reversep "Reverse " "")
                     regexp))
-       (goto-char opoint)
-       (narrow-to-region omin omax)
+       (rmail-show-message orig-message)
+       (if opoint (goto-char opoint))
        (ding)
        (message "Search failed: %s" regexp)))))
 
@@ -3259,93 +3121,72 @@ Interactively, empty argument means use same regexp used last time."
       (list rmail-search-last-regexp
            (prefix-numeric-value current-prefix-arg))))
   (rmail-search regexp (- (or n 1))))
+\f
+;; Scan for attributes, and compare subjects.
 
-;; Show the first message which has the `unseen' attribute.
 (defun rmail-first-unseen-message ()
+  "Return message number of first message which has `unseen' attribute."
   (rmail-maybe-set-message-counters)
   (let ((current 1)
        found)
     (save-restriction
       (widen)
       (while (and (not found) (<= current rmail-total-messages))
-       (if (rmail-message-labels-p current ", ?\\(unseen\\),")
+       (if (rmail-message-attr-p current "......U")
            (setq found current))
        (setq current (1+ current))))
-;; Let the caller show the message.
-;;    (if found
-;;     (rmail-show-message found))
     found))
 
-(defun rmail-current-subject ()
-  "Return the current subject.
-The subject is stripped of leading and trailing whitespace, and
-of typical reply prefixes such as Re:."
-  (let ((subject (or (mail-fetch-field "Subject") "")))
+(defun rmail-simplified-subject (&optional msgnum)
+  "Return the simplified subject of message MSGNUM (or current message).
+Simplifying the subject means stripping leading and trailing whitespace,
+and typical reply prefixes such as Re:."
+  (let ((subject (or (rmail-get-header "Subject" msgnum) "")))
     (if (string-match "\\`[ \t]+" subject)
        (setq subject (substring subject (match-end 0))))
     (if (string-match rmail-reply-regexp subject)
        (setq subject (substring subject (match-end 0))))
     (if (string-match "[ \t]+\\'" subject)
        (setq subject (substring subject 0 (match-beginning 0))))
+    ;; If Subject is long, mailers will break it into several lines at
+    ;; arbitrary places, so normalize whitespace by replacing every
+    ;; run of whitespace characters with a single space.
+    (setq subject (replace-regexp-in-string "[ \t\n]+" " " subject))
     subject))
 
-(defun rmail-current-subject-regexp ()
-  "Return a regular expression matching the current subject.
-The regular expression matches the subject header line of
-messages about the same subject.  The subject itself is stripped
-of leading and trailing whitespace, of typical reply prefixes
-such as Re: and whitespace within the subject is replaced by a
-regular expression matching whitespace in general in order to
-take into account that subject header lines may include newlines
-and more whitespace.  The returned regular expressions contains
-`rmail-reply-regexp' and ends with a newline."
-  (let ((subject (rmail-current-subject)))
-    ;; If Subject is long, mailers will break it into several lines at
-    ;; arbitrary places, so replace whitespace with a regexp that will
-    ;; match any sequence of spaces, TABs, and newlines.
+(defun rmail-simplified-subject-regexp ()
+  "Return a regular expression matching the current simplified subject.
+The idea is to match it against simplified subjects of other messages."
+  (let ((subject (rmail-simplified-subject)))
     (setq subject (regexp-quote subject))
+    ;; Hide commas so it will work ok if parsed as a comma-separated list
+    ;; of regexps.
     (setq subject
-         (replace-regexp-in-string "[ \t\n]+" "[ \t\n]+" subject t t))
-    ;; Some mailers insert extra spaces after "Subject:", so allow any
-    ;; amount of them.
-    (concat "^Subject:[ \t]+"
-           (if (string= "\\`" (substring rmail-reply-regexp 0 2))
-               (substring rmail-reply-regexp 2)
-             rmail-reply-regexp)
-           subject "[ \t]*\n")))
+         (replace-regexp-in-string "," "\054" subject t t))
+    (concat "\\`" subject "\\'")))
 
 (defun rmail-next-same-subject (n)
   "Go to the next mail message having the same subject header.
 With prefix argument N, do this N times.
 If N is negative, go backwards instead."
   (interactive "p")
-  (let ((search-regexp (rmail-current-subject-regexp))
+  (let ((subject (rmail-simplified-subject))
        (forward (> n 0))
        (i rmail-current-message)
-       (case-fold-search t)
        found)
-    (save-excursion
-      (save-restriction
-       (widen)
-       (while (and (/= n 0)
+    (while (and (/= n 0)
+               (if forward
+                   (< i rmail-total-messages)
+                 (> i 1)))
+      (let (done)
+       (while (and (not done)
                    (if forward
                        (< i rmail-total-messages)
                      (> i 1)))
-         (let (done)
-           (while (and (not done)
-                       (if forward
-                           (< i rmail-total-messages)
-                         (> i 1)))
-             (setq i (if forward (1+ i) (1- i)))
-             (goto-char (rmail-msgbeg i))
-             (search-forward "\n*** EOOH ***\n")
-             (let ((beg (point)) end)
-               (search-forward "\n\n")
-               (setq end (point))
-               (goto-char beg)
-               (setq done (re-search-forward search-regexp end t))))
-           (if done (setq found i)))
-         (setq n (if forward (1- n) (1+ n))))))
+         (setq i (if forward (1+ i) (1- i)))
+         (setq done (string-equal subject (rmail-simplified-subject i))))
+       (if done (setq found i)))
+      (setq n (if forward (1- n) (1+ n))))
     (if found
        (rmail-show-message found)
       (error "No %s message with same subject"
@@ -3361,15 +3202,18 @@ If N is negative, go forwards instead."
 ;;;; *** Rmail Message Deletion Commands ***
 
 (defun rmail-message-deleted-p (n)
+  "Return non-nil if message number N is deleted (in `rmail-deleted-vector')."
   (= (aref rmail-deleted-vector n) ?D))
 
 (defun rmail-set-message-deleted-p (n state)
-  (aset rmail-deleted-vector n (if state ?D ?\ )))
+  "Set the deleted state of message number N (in `rmail-deleted-vector').
+STATE non-nil means mark as deleted."
+  (aset rmail-deleted-vector n (if state ?D ?\s)))
 
 (defun rmail-delete-message ()
   "Delete this message and stay on it."
   (interactive)
-  (rmail-set-attribute "deleted" t)
+  (rmail-set-attribute rmail-deleted-attr-index t)
   (run-hooks 'rmail-delete-message-hook))
 
 (defun rmail-undelete-previous-message ()
@@ -3384,10 +3228,9 @@ If N is negative, go forwards instead."
        (error "No previous deleted message")
       (if (/= msg rmail-current-message)
          (rmail-show-message msg))
-      (rmail-set-attribute "deleted" nil)
+      (rmail-set-attribute rmail-deleted-attr-index nil)
       (if (rmail-summary-exists)
-         (save-excursion
-           (set-buffer rmail-summary-buffer)
+         (with-current-buffer rmail-summary-buffer
            (rmail-summary-mark-undeleted msg)))
       (rmail-maybe-display-summary))))
 
@@ -3398,7 +3241,7 @@ With prefix argument, delete and move backward.
 
 Returns t if a new message is displayed after the delete, or nil otherwise."
   (interactive "P")
-  (rmail-set-attribute "deleted" t)
+  (rmail-set-attribute rmail-deleted-attr-index t)
   (run-hooks 'rmail-delete-message-hook)
   (let ((del-msg rmail-current-message))
     (if (rmail-summary-exists)
@@ -3412,6 +3255,8 @@ Returns t if a new message is displayed after the delete, or nil otherwise."
 Deleted messages stay in the file until the \\[rmail-expunge] command is given."
   (interactive)
   (rmail-delete-forward t))
+\f
+;; Expunging.
 
 ;; Compute the message number a given message would have after expunging.
 ;; The present number of the message is OLDNUM.
@@ -3429,18 +3274,20 @@ Deleted messages stay in the file until the \\[rmail-expunge] command is given."
       newnum)))
 
 (defun rmail-expunge-confirmed ()
-  "Return t if deleted message should be expunged. If necessary, ask the user.
-See also user-option `rmail-confirm-expunge'."
+  "Return t if expunge is needed and desirable.
+If `rmail-confirm-expunge' is non-nil, ask user to confirm."
   (set-buffer rmail-buffer)
-  (or (not (stringp rmail-deleted-vector))
-      (not (string-match "D" rmail-deleted-vector))
-      (null rmail-confirm-expunge)
-      (funcall rmail-confirm-expunge
-              "Erase deleted messages from Rmail file? ")))
+  (and (stringp rmail-deleted-vector)
+       (string-match "D" rmail-deleted-vector)
+       (if rmail-confirm-expunge
+          (funcall rmail-confirm-expunge
+                   "Erase deleted messages from Rmail file? ")
+        t)))
 
 (defun rmail-only-expunge (&optional dont-show)
   "Actually erase all deleted messages in the file."
   (interactive)
+  (rmail-swap-buffers-maybe)
   (set-buffer rmail-buffer)
   (message "Expunging deleted messages...")
   ;; Discard all undo records for this buffer.
@@ -3467,12 +3314,11 @@ See also user-option `rmail-confirm-expunge'."
          (goto-char (point-min))
          (let ((counter 0)
                (number 1)
-               (total rmail-total-messages)
-               (new-message-number rmail-current-message)
-               (new-summary nil)
+               new-summary
                (new-msgref (list (list 0)))
-               (rmailbuf (current-buffer))
                (buffer-read-only nil)
+               (total rmail-total-messages)
+               (new-message-number rmail-current-message)
                (messages rmail-message-vector)
                (deleted rmail-deleted-vector)
                (summary rmail-summary-vector))
@@ -3485,9 +3331,8 @@ See also user-option `rmail-confirm-expunge'."
            (while (<= number total)
              (if (= (aref deleted number) ?D)
                  (progn
-                   (delete-region
-                     (marker-position (aref messages number))
-                     (marker-position (aref messages (1+ number))))
+                   (delete-region (aref messages number)
+                                  (aref messages (1+ number)))
                    (move-marker (aref messages number) nil)
                    (if (> new-message-number counter)
                        (setq new-message-number (1- new-message-number))))
@@ -3510,7 +3355,7 @@ See also user-option `rmail-confirm-expunge'."
            (setq rmail-current-message new-message-number
                  rmail-total-messages counter
                  rmail-message-vector (apply 'vector messages-head)
-                 rmail-deleted-vector (make-string (1+ counter) ?\ )
+                 rmail-deleted-vector (make-string (1+ counter) ?\s)
                  rmail-summary-vector (vconcat (nreverse new-summary))
                  rmail-msgref-vector (apply 'vector (nreverse new-msgref))
                  win t)))
@@ -3518,19 +3363,49 @@ See also user-option `rmail-confirm-expunge'."
       (if (not win)
          (narrow-to-region (- (buffer-size) omin) (- (buffer-size) omax)))
       (if (not dont-show)
-         (rmail-show-message
-          (if (zerop rmail-current-message) 1 nil)))
+         (rmail-show-message (min rmail-current-message rmail-total-messages)))
       (if rmail-enable-mime
          (goto-char (+ (point-min) opoint))
        (goto-char (+ (point) opoint))))))
 
-(defun rmail-expunge ()
-  "Erase deleted messages from Rmail file and summary buffer."
+;; The DONT-SHOW argument is new in 23.  Does not seem very important.
+(defun rmail-expunge (&optional dont-show)
+  "Erase deleted messages from Rmail file and summary buffer.
+This always shows a message (so as not to leave the Rmail buffer
+unswapped), and always updates any summary (so that it remains
+consistent with the Rmail buffer).  If DONT-SHOW is non-nil, it
+does not pop any summary buffer."
   (interactive)
   (when (rmail-expunge-confirmed)
-    (rmail-only-expunge)
-    (if (rmail-summary-exists)
-       (rmail-select-summary (rmail-update-summary)))))
+    (rmail-modify-format)
+    (let ((was-deleted (rmail-message-deleted-p rmail-current-message))
+         (was-swapped (rmail-buffers-swapped-p)))
+      (rmail-only-expunge t)
+      ;; We always update the summary buffer, so that the contents
+      ;; remain consistent with the rmail buffer.
+      ;; The only difference is, in the dont-show case, we use a
+      ;; cut-down version of rmail-select-summary that does not pop
+      ;; the summary buffer.  It's only used by rmail-quit, which is
+      ;; just going to bury any summary immediately after.  If we made
+      ;; rmail-quit bury the summary first, dont-show could be removed.
+      ;; But the expunge might not be confirmed...
+      (if (rmail-summary-exists)
+         (if dont-show
+             (let ((total rmail-total-messages))
+               (with-current-buffer rmail-summary-buffer
+                 (let ((rmail-total-messages total))
+                   (rmail-update-summary))))
+           (rmail-select-summary (rmail-update-summary))))
+      ;; We always show a message, because (rmail-only-expunge t)
+      ;; leaves the rmail buffer unswapped.
+      ;; If we expunged the current message, a new one is current now,
+      ;; so show it.  If we weren't showing a message, show it.
+      (if (or was-deleted (not was-swapped))
+         (rmail-show-message-1 rmail-current-message)
+       ;; We can just show the same message that was being shown before.
+       (rmail-display-labels)
+       (rmail-swap-buffers)
+       (setq rmail-buffer-swapped t)))))
 \f
 ;;;; *** Rmail Mailing Commands ***
 
@@ -3538,6 +3413,8 @@ See also user-option `rmail-confirm-expunge'."
                                   replybuffer sendactions same-window others)
   (let (yank-action)
     (if replybuffer
+       ;; The function used here must behave like insert-buffer wrt
+       ;; point and mark (see doc of sc-cite-original).
        (setq yank-action (list 'insert-buffer replybuffer)))
     (setq others (cons (cons "cc" cc) others))
     (setq others (cons (cons "in-reply-to" in-reply-to) others))
@@ -3565,6 +3442,7 @@ original message into it."
   (interactive)
   (rmail-start-mail nil nil nil nil nil rmail-view-buffer))
 
+;; FIXME should complain if there is nothing to continue.
 (defun rmail-continue ()
   "Continue composing outgoing message previously being composed."
   (interactive)
@@ -3576,64 +3454,50 @@ Normally include CC: to all other recipients of original message;
 prefix argument means ignore them.  While composing the reply,
 use \\[mail-yank-original] to yank the original message into it."
   (interactive "P")
+  (if (zerop rmail-current-message)
+      (error "There is no message to reply to"))
   (let (from reply-to cc subject date to message-id references
             resent-to resent-cc resent-reply-to
             (msgnum rmail-current-message))
-    (save-excursion
-      (save-restriction
-       (if rmail-enable-mime
-           (narrow-to-region
-            (goto-char (point-min))
-            (if (search-forward "\n\n" nil 'move)
-                (1+ (match-beginning 0))
-              (point)))
-         (widen)
-         (goto-char (rmail-msgbeg rmail-current-message))
-         (forward-line 1)
-         (if (= (following-char) ?0)
-             (narrow-to-region
-              (progn (forward-line 2)
-                     (point))
-              (progn (search-forward "\n\n" (rmail-msgend rmail-current-message)
-                                     'move)
-                     (point)))
-           (narrow-to-region (point)
-                             (progn (search-forward "\n*** EOOH ***\n")
-                                    (beginning-of-line) (point)))))
-       (setq from (mail-fetch-field "from")
-             reply-to (or (mail-fetch-field "mail-reply-to" nil t)
-                          (mail-fetch-field "reply-to" nil t)
-                          from)
-             subject (mail-fetch-field "subject")
-             date (mail-fetch-field "date")
-             message-id (mail-fetch-field "message-id")
-             references (mail-fetch-field "references" nil nil t)
-             resent-reply-to (mail-fetch-field "resent-reply-to" nil t)
-             resent-cc (and (not just-sender)
-                            (mail-fetch-field "resent-cc" nil t))
-             resent-to (or (mail-fetch-field "resent-to" nil t) "")
-;;;          resent-subject (mail-fetch-field "resent-subject")
-;;;          resent-date (mail-fetch-field "resent-date")
-;;;          resent-message-id (mail-fetch-field "resent-message-id")
-             )
-       (unless just-sender
-         (if (mail-fetch-field "mail-followup-to" nil t)
-             ;; If this header field is present, use it instead of the To and CC fields.
-             (setq to (mail-fetch-field "mail-followup-to" nil t))
-           (setq cc (or (mail-fetch-field "cc" nil t) "")
-                 to (or (mail-fetch-field "to" nil t) ""))))
-
-       ))
-
+    (rmail-apply-in-message
+     rmail-current-message
+     (lambda ()
+       (search-forward "\n\n" nil 'move)
+       (narrow-to-region (point-min) (point))
+       (setq from (mail-fetch-field "from")
+            reply-to (or (mail-fetch-field "mail-reply-to" nil t)
+                         (mail-fetch-field "reply-to" nil t)
+                         from)
+            subject (mail-fetch-field "subject")
+            date (mail-fetch-field "date")
+            message-id (mail-fetch-field "message-id")
+            references (mail-fetch-field "references" nil nil t)
+            resent-reply-to (mail-fetch-field "resent-reply-to" nil t)
+            ;; Bug#512.  It's inappropriate to reply to these addresses.
+;;;         resent-cc (and (not just-sender)
+;;;                        (mail-fetch-field "resent-cc" nil t))
+;;;         resent-to (or (mail-fetch-field "resent-to" nil t) "")
+;;;         resent-subject (mail-fetch-field "resent-subject")
+;;;         resent-date (mail-fetch-field "resent-date")
+;;;         resent-message-id (mail-fetch-field "resent-message-id")
+            )
+       (unless just-sender
+        (if (mail-fetch-field "mail-followup-to" nil t)
+            ;; If this header field is present, use it instead of the
+            ;; To and CC fields.
+            (setq to (mail-fetch-field "mail-followup-to" nil t))
+          (setq cc (or (mail-fetch-field "cc" nil t) "")
+                to (or (mail-fetch-field "to" nil t) ""))))))
     ;; Merge the resent-to and resent-cc into the to and cc.
-    (if (and resent-to (not (equal resent-to "")))
-       (if (not (equal to ""))
-           (setq to (concat to ", " resent-to))
-         (setq to resent-to)))
-    (if (and resent-cc (not (equal resent-cc "")))
-       (if (not (equal cc ""))
-           (setq cc (concat cc ", " resent-cc))
-         (setq cc resent-cc)))
+    ;; Bug#512.  It's inappropriate to reply to these addresses.
+;;;    (if (and resent-to (not (equal resent-to "")))
+;;;    (if (not (equal to ""))
+;;;        (setq to (concat to ", " resent-to))
+;;;      (setq to resent-to)))
+;;;    (if (and resent-cc (not (equal resent-cc "")))
+;;;    (if (not (equal cc ""))
+;;;        (setq cc (concat cc ", " resent-cc))
+;;;      (setq cc resent-cc)))
     ;; Add `Re: ' to subject if not there already.
     (and (stringp subject)
         (setq subject
@@ -3664,23 +3528,26 @@ use \\[mail-yank-original] to yank the original message into it."
                        (mail-strip-quoted-names
                         (if (null cc) to (concat to ", " cc))))))
         (if (string= cc-list "") nil cc-list)))
-     rmail-view-buffer
+     (if (rmail-buffers-swapped-p)
+        rmail-buffer
+       rmail-view-buffer)
      (list (list 'rmail-mark-message
                 rmail-buffer
                 (with-current-buffer rmail-buffer
                   (aref rmail-msgref-vector msgnum))
-                "answered"))
+                rmail-answered-attr-index))
      nil
-     (list (cons "References" (concat (mapconcat 'identity references " ")
-                                     " " message-id))))))
-
+     (list (cons "References" (if references
+                                 (concat (mapconcat 'identity references " ")
+                                         " " message-id)
+                               message-id))))))
+\f
 (defun rmail-mark-message (buffer msgnum-list attribute)
   "Give BUFFER's message number in MSGNUM-LIST the attribute ATTRIBUTE.
 This is use in the send-actions for message buffers.
 MSGNUM-LIST is a list of the form (MSGNUM)
 which is an element of rmail-msgref-vector."
-  (save-excursion
-    (set-buffer buffer)
+  (with-current-buffer buffer
     (if (car msgnum-list)
        (rmail-set-attribute attribute t (car msgnum-list)))))
 
@@ -3727,10 +3594,10 @@ which is an element of rmail-msgref-vector."
                (end (match-end 1)))
            ;; Trim whitespace which above regexp match allows
            (while (and (< start end)
-                       (memq (aref from start) '(?\t ?\ )))
+                       (memq (aref from start) '(?\t ?\s)))
              (setq start (1+ start)))
            (while (and (< start end)
-                       (memq (aref from (1- end)) '(?\t ?\ )))
+                       (memq (aref from (1- end)) '(?\t ?\s)))
              (setq end (1- end)))
            (let ((field (substring from start end)))
              (if date (setq field (concat "message from " field " on " date)))
@@ -3766,7 +3633,7 @@ see the documentation of `rmail-resend'."
                       forward-buffer
                       (with-current-buffer rmail-buffer
                         (aref rmail-msgref-vector msgnum))
-                      "forwarded"))
+                      rmail-forwarded-attr-index))
           ;; If only one window, use it for the mail buffer.
           ;; Otherwise, use another window for the mail buffer
           ;; so that the Rmail buffer remains visible
@@ -3825,7 +3692,9 @@ typically for purposes of moderating a list."
        (with-current-buffer tembuf
          ;;>> Copy message into temp buffer
          (if rmail-enable-mime
-             (funcall rmail-insert-mime-resent-message-function mailbuf)
+              (if rmail-insert-mime-resent-message-function
+                  (funcall rmail-insert-mime-resent-message-function mailbuf)
+                (error "You must set `rmail-insert-mime-resent-message-function'"))
            (insert-buffer-substring mailbuf))
          (goto-char (point-min))
          ;; Delete any Sender field, since that's not specifiable.
@@ -3890,7 +3759,7 @@ typically for purposes of moderating a list."
            (funcall send-mail-function)))
       (kill-buffer tembuf))
     (with-current-buffer rmail-buffer
-      (rmail-set-attribute "resent" t rmail-current-message))))
+      (rmail-set-attribute rmail-resent-attr-index t rmail-current-message))))
 \f
 (defvar mail-unsent-separator
   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
@@ -3909,6 +3778,25 @@ typically for purposes of moderating a list."
 (defvar mail-mime-unsent-header "^Content-Type: message/rfc822 *$"
  "A regexp that matches the header of a MIME body part with a failed message.")
 
+;; This is a cut-down version of rmail-clear-headers from Emacs 22.
+;; It doesn't have the same functionality, hence the name change.
+(defun rmail-delete-headers (regexp)
+  "Delete any mail headers matching REGEXP.
+The message should be narrowed to just the headers."
+  (when regexp
+    (goto-char (point-min))
+    (while (re-search-forward regexp nil t)
+      (beginning-of-line)
+      ;; This code from Emacs 22 doesn't seem right, since r-n-h is
+      ;; just for display.
+;;;      (if (looking-at rmail-nonignored-headers)
+;;;      (forward-line 1)
+      (delete-region (point)
+                    (save-excursion
+                      (if (re-search-forward "\n[^ \t]" nil t)
+                          (1- (point))
+                        (point-max)))))))
+
 (defun rmail-retry-failure ()
   "Edit a mail message which is based on the contents of the current message.
 For a message rejected by the mail system, extract the interesting headers and
@@ -3924,13 +3812,7 @@ specifying headers which should not be copied into the new message."
   (let ((rmail-this-buffer (current-buffer))
        (msgnum rmail-current-message)
        bounce-start bounce-end bounce-indent resending
-       ;; Fetch any content-type header in current message
-       ;; Must search thru the whole unpruned header.
-       (content-type
-        (save-excursion
-          (save-restriction
-            (rmail-narrow-to-non-pruned-header)
-            (mail-fetch-field "Content-Type") ))))
+       (content-type (rmail-get-header "Content-Type")))
     (save-excursion
       (goto-char (point-min))
       (let ((case-fold-search t))
@@ -3995,24 +3877,22 @@ specifying headers which should not be copied into the new message."
                            (list (list 'rmail-mark-message
                                        rmail-this-buffer
                                        (aref rmail-msgref-vector msgnum)
-                                       "retried")))
+                                       rmail-retried-attr-index)))
          ;; Insert original text as initial text of new draft message.
          ;; Bind inhibit-read-only since the header delimiter
          ;; of the previous message was probably read-only.
-         (let ((inhibit-read-only t)
-               rmail-displayed-headers
-               rmail-ignored-headers)
+         (let ((inhibit-read-only t))
            (erase-buffer)
            (insert-buffer-substring rmail-this-buffer
                                     bounce-start bounce-end)
            (goto-char (point-min))
            (if bounce-indent
                (indent-rigidly (point-min) (point-max) bounce-indent))
-           (rmail-clear-headers rmail-retry-ignored-headers)
-           (rmail-clear-headers "^sender:\\|^return-path:\\|^received:")
            (mail-sendmail-delimit-header)
            (save-restriction
              (narrow-to-region (point-min) (mail-header-end))
+             (rmail-delete-headers rmail-retry-ignored-headers)
+             (rmail-delete-headers "^\\(sender\\|return-path\\|received\\):")
              (setq resending (mail-fetch-field "resent-to"))
              (if mail-self-blind
                  (if resending
@@ -4032,13 +3912,13 @@ In fact, the non-nil value returned is the summary buffer itself."
   (and rmail-summary-buffer (get-buffer-window rmail-summary-buffer)))
 
 (defcustom rmail-redisplay-summary nil
-  "*Non-nil means Rmail should show the summary when it changes.
+  "Non-nil means Rmail should show the summary when it changes.
 This has an effect only if a summary buffer exists."
   :type 'boolean
   :group 'rmail-summary)
 
 (defcustom rmail-summary-window-size nil
-  "*Non-nil means specify the height for an Rmail summary window."
+  "Non-nil means specify the height for an Rmail summary window."
   :type '(choice (const :tag "Disabled" nil) integer)
   :group 'rmail-summary)
 
@@ -4089,7 +3969,8 @@ This has an effect only if a summary buffer exists."
       (remove-hook 'rmail-show-message-hook 'rmail-fontify-message t)
       (remove-text-properties (point-min) (point-max) '(rmail-fontified nil))
       (font-lock-default-unfontify-buffer)
-      (and (not modified) (buffer-modified-p) (set-buffer-modified-p nil)))))
+      (and (not modified) (buffer-modified-p)
+           (restore-buffer-modified-p nil)))))
 
 (defun rmail-fontify-message ()
   ;; Fontify the current message if it is not already fontified.
@@ -4102,7 +3983,8 @@ This has an effect only if a summary buffer exists."
          (save-match-data
            (add-text-properties (point-min) (point-max) '(rmail-fontified t))
            (font-lock-fontify-region (point-min) (point-max))
-           (and (not modified) (buffer-modified-p) (set-buffer-modified-p nil)))))))
+           (and (not modified) (buffer-modified-p)
+                 (restore-buffer-modified-p nil)))))))
 \f
 ;;; Speedbar support for RMAIL files.
 (eval-when-compile (require 'speedbar))
@@ -4130,6 +4012,7 @@ browsing, and moving of messages.")
     (define-key rmail-speedbar-key-map "M"
       'rmail-speedbar-move-message-to-folder-on-line)))
 
+;; Mouse-3.
 (defvar rmail-speedbar-menu-items
   '(["Read Folder" speedbar-edit-line t]
     ["Move message to folder" rmail-speedbar-move-message-to-folder-on-line
@@ -4148,17 +4031,14 @@ Click on the address under Reply to: to reply to this person.
 Under Folders: Click a name to read it, or on the <M> to move the
 current message into that RMAIL folder."
   (let ((from nil))
-    (save-excursion
-      (set-buffer buffer)
+    (with-current-buffer buffer
       (goto-char (point-min))
       (if (not (re-search-forward "^Reply-To: " nil t))
          (if (not (re-search-forward "^From:? " nil t))
              (setq from t)))
       (if from
          nil
-       (setq from (buffer-substring (point) (save-excursion
-                                              (end-of-line)
-                                              (point))))))
+       (setq from (buffer-substring (point) (line-end-position)))))
     (goto-char (point-min))
     (if (and (looking-at "Reply to:")
             (equal from rmail-speedbar-last-user))
@@ -4171,15 +4051,15 @@ current message into that RMAIL folder."
                                  'rmail-speedbar-button 'rmail-reply))
       (insert "Folders:\n")
       (let* ((case-fold-search nil)
-            (df (directory-files (save-excursion (set-buffer buffer)
-                                                 default-directory)
+            (df (directory-files (with-current-buffer buffer
+                                    default-directory)
                                  nil rmail-speedbar-match-folder-regexp)))
-       (while df
-         (speedbar-insert-button "<M>" 'speedbar-button-face 'highlight
-                                 'rmail-speedbar-move-message (car df))
-         (speedbar-insert-button (car df) 'speedbar-file-face 'highlight
-                                 'rmail-speedbar-find-file nil t)
-         (setq df (cdr df)))))))
+       (dolist (file df)
+         (when (file-regular-p file)
+           (speedbar-insert-button "<M>" 'speedbar-button-face 'highlight
+                                   'rmail-speedbar-move-message file)
+           (speedbar-insert-button file 'speedbar-file-face 'highlight
+                                   'rmail-speedbar-find-file nil t)))))))
 
 (defun rmail-speedbar-button (text token indent)
   "Execute an rmail command specified by TEXT.
@@ -4192,14 +4072,14 @@ The command used is TOKEN.  INDENT is not used."
 TOKEN and INDENT are not used."
   (speedbar-with-attached-buffer
    (message "Loading in RMAIL file %s..." text)
-   (find-file text)))
+   (rmail text)))
 
 (defun rmail-speedbar-move-message-to-folder-on-line ()
   "If the current line is a folder, move current message to it."
   (interactive)
   (save-excursion
     (beginning-of-line)
-    (if (re-search-forward "<M> " (save-excursion (end-of-line) (point)) t)
+    (if (re-search-forward "<M> " (line-end-position) t)
        (progn
          (forward-char -2)
          (speedbar-do-function-pointer)))))
@@ -4209,12 +4089,15 @@ TOKEN and INDENT are not used."
 TEXT and INDENT are not used."
   (speedbar-with-attached-buffer
    (message "Moving message to %s" token)
-   (rmail-output-to-rmail-file token)))
+   ;; expand-file-name is needed due to the unhelpful way in which
+   ;; rmail-output expands non-absolute filenames against rmail-default-file.
+   ;; What is the point of that, anyway?
+   (rmail-output (expand-file-name token))))
 
-; Functions for setting, getting and encoding the POP password.
-; The password is encoded to prevent it from being easily accessible
-; to "prying eyes."  Obviously, this encoding isn't "real security,"
-; nor is it meant to be.
+;; Functions for setting, getting and encoding the POP password.
+;; The password is encoded to prevent it from being easily accessible
+;; to "prying eyes."  Obviously, this encoding isn't "real security,"
+;; nor is it meant to be.
 
 ;;;###autoload
 (defun rmail-set-remote-password (password)
@@ -4264,15 +4147,15 @@ encoded string (and the same mask) will decode the string."
 ;;;;  Desktop support
 
 (defun rmail-restore-desktop-buffer (desktop-buffer-file-name
-                                     desktop-buffer-name
-                                     desktop-buffer-misc)
+                                    desktop-buffer-name
+                                    desktop-buffer-misc)
   "Restore an rmail buffer specified in a desktop file."
   (condition-case error
       (progn
-        (rmail-input desktop-buffer-file-name)
-        (if (eq major-mode 'rmail-mode)
-            (current-buffer)
-          rmail-buffer))
+       (rmail-input desktop-buffer-file-name)
+       (if (eq major-mode 'rmail-mode)
+           (current-buffer)
+         rmail-buffer))
     (file-locked
       (kill-buffer (current-buffer))
       nil)))
@@ -4280,7 +4163,233 @@ encoded string (and the same mask) will decode the string."
 (add-to-list 'desktop-buffer-mode-handlers
             '(rmail-mode . rmail-restore-desktop-buffer))
 
+;; Used in `write-region-annotate-functions' to write rmail files.
+(defun rmail-write-region-annotate (start end)
+  (when (and (null start) (rmail-buffers-swapped-p))
+    (set-buffer rmail-view-buffer)
+    (widen)
+    nil))
+
+\f
+;;; Start of automatically extracted autoloads.
+\f
+;;;### (autoloads (rmail-edit-current-message) "rmailedit" "rmailedit.el"
+;;;;;;  "c70c6c35b8c5bbdb73787a48b83e5adc")
+;;; Generated autoloads from rmailedit.el
+
+(autoload 'rmail-edit-current-message "rmailedit" "\
+Edit the contents of this message.
+
+\(fn)" t nil)
+
+;;;***
+\f
+;;;### (autoloads (rmail-next-labeled-message rmail-previous-labeled-message
+;;;;;;  rmail-read-label rmail-kill-label rmail-add-label) "rmailkwd"
+;;;;;;  "rmailkwd.el" "2e986921026eea971b49e91f53967f77")
+;;; Generated autoloads from rmailkwd.el
+
+(autoload 'rmail-add-label "rmailkwd" "\
+Add LABEL to labels associated with current RMAIL message.
+Completes (see `rmail-read-label') over known labels when reading.
+LABEL may be a symbol or string.  Only one label is allowed.
+
+\(fn LABEL)" t nil)
+
+(autoload 'rmail-kill-label "rmailkwd" "\
+Remove LABEL from labels associated with current RMAIL message.
+Completes (see `rmail-read-label') over known labels when reading.
+LABEL may be a symbol or string.  Only one label is allowed.
+
+\(fn LABEL)" t nil)
+
+(autoload 'rmail-read-label "rmailkwd" "\
+Read a label with completion, prompting with PROMPT.
+Completions are chosen from `rmail-label-obarray'.  The default
+is `rmail-last-label', if that is non-nil.  Updates `rmail-last-label'
+according to the choice made, and returns a symbol.
+
+\(fn PROMPT)" nil nil)
+
+(autoload 'rmail-previous-labeled-message "rmailkwd" "\
+Show previous message with one of the labels LABELS.
+LABELS should be a comma-separated list of label names.
+If LABELS is empty, the last set of labels specified is used.
+With prefix argument N moves backward N messages with these labels.
+
+\(fn N LABELS)" t nil)
+
+(autoload 'rmail-next-labeled-message "rmailkwd" "\
+Show next message with one of the labels LABELS.
+LABELS should be a comma-separated list of label names.
+If LABELS is empty, the last set of labels specified is used.
+With prefix argument N moves forward N messages with these labels.
+
+\(fn N LABELS)" t nil)
+
+;;;***
+\f
+;;;### (autoloads (rmail-mime) "rmailmm" "rmailmm.el" "ae80368d7bee6d397e916de369676b29")
+;;; Generated autoloads from rmailmm.el
+
+(autoload 'rmail-mime "rmailmm" "\
+Process the current Rmail message as a MIME message.
+This creates a temporary \"*RMAIL*\" buffer holding a decoded
+copy of the message.  Content-types are handled according to
+`rmail-mime-media-type-handlers-alist'.  By default, this
+displays text and multipart messages, and offers to download
+attachments as specfied by `rmail-mime-attachment-dirs-alist'.
+
+\(fn)" t nil)
+
+;;;***
+\f
+;;;### (autoloads (set-rmail-inbox-list) "rmailmsc" "rmailmsc.el"
+;;;;;;  "de01c37c81339201034a01732b97f44e")
+;;; Generated autoloads from rmailmsc.el
+
+(autoload 'set-rmail-inbox-list "rmailmsc" "\
+Set the inbox list of the current RMAIL file to FILE-NAME.
+You can specify one file name, or several names separated by commas.
+If FILE-NAME is empty, remove any existing inbox list.
+
+This applies only to the current session.
+
+\(fn FILE-NAME)" t nil)
+
+;;;***
+\f
+;;;### (autoloads (rmail-sort-by-labels rmail-sort-by-lines rmail-sort-by-correspondent
+;;;;;;  rmail-sort-by-recipient rmail-sort-by-author rmail-sort-by-subject
+;;;;;;  rmail-sort-by-date) "rmailsort" "rmailsort.el" "3f2b10b0272ea56cb604f29330d95fc4")
+;;; Generated autoloads from rmailsort.el
+
+(autoload 'rmail-sort-by-date "rmailsort" "\
+Sort messages of current Rmail buffer by \"Date\" header.
+If prefix argument REVERSE is non-nil, sorts in reverse order.
+
+\(fn REVERSE)" t nil)
+
+(autoload 'rmail-sort-by-subject "rmailsort" "\
+Sort messages of current Rmail buffer by \"Subject\" header.
+Ignores any \"Re: \" prefix.  If prefix argument REVERSE is
+non-nil, sorts in reverse order.
+
+\(fn REVERSE)" t nil)
+
+(autoload 'rmail-sort-by-author "rmailsort" "\
+Sort messages of current Rmail buffer by author.
+This uses either the \"From\" or \"Sender\" header, downcased.
+If prefix argument REVERSE is non-nil, sorts in reverse order.
+
+\(fn REVERSE)" t nil)
+
+(autoload 'rmail-sort-by-recipient "rmailsort" "\
+Sort messages of current Rmail buffer by recipient.
+This uses either the \"To\" or \"Apparently-To\" header, downcased.
+If prefix argument REVERSE is non-nil, sorts in reverse order.
+
+\(fn REVERSE)" t nil)
+
+(autoload 'rmail-sort-by-correspondent "rmailsort" "\
+Sort messages of current Rmail buffer by other correspondent.
+This uses either the \"From\", \"Sender\", \"To\", or
+\"Apparently-To\" header, downcased.  Uses the first header not
+excluded by `rmail-dont-reply-to-names'.  If prefix argument
+REVERSE is non-nil, sorts in reverse order.
+
+\(fn REVERSE)" t nil)
+
+(autoload 'rmail-sort-by-lines "rmailsort" "\
+Sort messages of current Rmail buffer by the number of lines.
+If prefix argument REVERSE is non-nil, sorts in reverse order.
+
+\(fn REVERSE)" t nil)
+
+(autoload 'rmail-sort-by-labels "rmailsort" "\
+Sort messages of current Rmail buffer by labels.
+LABELS is a comma-separated list of labels.  The order of these
+labels specifies the order of messages: messages with the first
+label come first, messages with the second label come second, and
+so on.  Messages that have none of these labels come last.
+If prefix argument REVERSE is non-nil, sorts in reverse order.
+
+\(fn REVERSE LABELS)" t nil)
+
+;;;***
+\f
+;;;### (autoloads (rmail-summary-by-senders rmail-summary-by-topic
+;;;;;;  rmail-summary-by-regexp rmail-summary-by-recipients rmail-summary-by-labels
+;;;;;;  rmail-summary) "rmailsum" "rmailsum.el" "60bec0ae88b7ed18dd6845ddb9ccd904")
+;;; Generated autoloads from rmailsum.el
+
+(autoload 'rmail-summary "rmailsum" "\
+Display a summary of all messages, one line per message.
+
+\(fn)" t nil)
+
+(autoload 'rmail-summary-by-labels "rmailsum" "\
+Display a summary of all messages with one or more LABELS.
+LABELS should be a string containing the desired labels, separated by commas.
+
+\(fn LABELS)" t nil)
+
+(autoload 'rmail-summary-by-recipients "rmailsum" "\
+Display a summary of all messages with the given RECIPIENTS.
+Normally checks the To, From and Cc fields of headers;
+but if PRIMARY-ONLY is non-nil (prefix arg given),
+ only look in the To and From fields.
+RECIPIENTS is a string of regexps separated by commas.
+
+\(fn RECIPIENTS &optional PRIMARY-ONLY)" t nil)
+
+(autoload 'rmail-summary-by-regexp "rmailsum" "\
+Display a summary of all messages according to regexp REGEXP.
+If the regular expression is found in the header of the message
+\(including in the date and other lines, as well as the subject line),
+Emacs will list the message in the summary.
+
+\(fn REGEXP)" t nil)
+
+(autoload 'rmail-summary-by-topic "rmailsum" "\
+Display a summary of all messages with the given SUBJECT.
+Normally checks just the Subject field of headers; but with prefix
+argument WHOLE-MESSAGE is non-nil, looks in the whole message.
+SUBJECT is a string of regexps separated by commas.
+
+\(fn SUBJECT &optional WHOLE-MESSAGE)" t nil)
+
+(autoload 'rmail-summary-by-senders "rmailsum" "\
+Display a summary of all messages whose \"From\" field matches SENDERS.
+SENDERS is a string of regexps separated by commas.
+
+\(fn SENDERS)" t nil)
+
+;;;***
+\f
+;;;### (autoloads (unforward-rmail-message undigestify-rmail-message)
+;;;;;;  "undigest" "undigest.el" "b691540ddff5c394e9ebc3517051445f")
+;;; Generated autoloads from undigest.el
+
+(autoload 'undigestify-rmail-message "undigest" "\
+Break up a digest message into its constituent messages.
+Leaves original message, deleted, before the undigestified messages.
+
+\(fn)" t nil)
+
+(autoload 'unforward-rmail-message "undigest" "\
+Extract a forwarded message from the containing message.
+This puts the forwarded message into a separate rmail message
+following the containing message.
+
+\(fn)" t nil)
+
+;;;***
+\f
+;;; End of automatically extracted autoloads.
+
+
 (provide 'rmail)
 
-;; arch-tag: cff0a950-57fe-4f73-a86e-91ff75afd06c
+;; arch-tag: 65d257d3-c281-4a65-9c38-e61af95af2f0
 ;;; rmail.el ends here