rmail.el 142 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
;;; 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, 2009
;;   Free Software Foundation, Inc.

;; Maintainer: FSF
;; Keywords: mail

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;;; Code:

;; Souped up by shane@mit-ajax based on ideas of rlk@athena.mit.edu
;;   New features include attribute and keyword support, message
;;   selection by dispatch table, summary by attributes and keywords,
;;   expunging by dispatch table, sticky options for file commands.

;; Extended by Bob Weiner of Motorola
;;   New features include: rmail and rmail-summary buffers remain
;;   synchronized and key bindings basically operate the same way in both
;;   buffers, summary by topic or by regular expression, rmail-reply-prefix
;;   variable, and a bury rmail buffer (wipe) command.
;;

(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 6
  "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)

(defvar rmail-header-style 'normal
  "The current header display style choice, one of
'normal (selected headers) or 'full (all headers).")

; 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")
;  "")

;; Temporary support for mbox.
(defcustom rmail-file-name "~/RMAIL"
113
  "Name of user's primary mail file."
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  :type 'string
  :group 'rmail
  :version "21.1")

(defgroup rmail nil
  "Mail reader for Emacs."
  :group 'mail)

(defgroup rmail-retrieve nil
  "Rmail retrieval options."
  :prefix "rmail-"
  :group 'rmail)

(defgroup rmail-files nil
  "Rmail files."
  :prefix "rmail-"
  :group 'rmail)

(defgroup rmail-headers nil
  "Rmail header options."
  :prefix "rmail-"
  :group 'rmail)

(defgroup rmail-reply nil
  "Rmail reply options."
  :prefix "rmail-"
  :group 'rmail)

(defgroup rmail-summary nil
  "Rmail summary options."
  :prefix "rmail-"
  :prefix "rmail-summary-"
  :group 'rmail)

(defgroup rmail-output nil
  "Output message to a file."
  :prefix "rmail-output-"
  :prefix "rmail-"
  :group 'rmail)

(defgroup rmail-edit nil
  "Rmail editing."
  :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
169
  "Password to use when reading mail from POP server.
170 171 172 173 174 175
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
176
  "Non-nil if a password is required when reading mail from a POP server.
177 178 179 180 181
Please use rmail-remote-password-required instead."
  :type 'boolean
  :group 'rmail-obsolete)

(defcustom rmail-remote-password nil
182
  "Password to use when reading mail from a remote server.
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
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")

(defcustom rmail-remote-password-required nil
199
  "Non-nil if a password is required when reading mail from a remote server."
200 201 202 203 204 205 206 207 208 209 210 211 212 213
  :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
214
  "List of flags to pass to movemail.
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
Most commonly used to specify `-g' to enable GSS-API authentication
or `-k' to enable Kerberos authentication."
  :type '(repeat string)
  :group 'rmail-retrieve
  :version "20.3")

(defvar rmail-remote-password-error "invalid usercode or password\\|
unknown user name or bad password\\|Authentication failed\\|MU_ERR_AUTH_FAILURE"
  "Regular expression matching incorrect-password POP or IMAP server error
messages.
If you get an incorrect-password error that this expression does not match,
please report it with \\[report-emacs-bug].")

(defvar rmail-encoded-remote-password nil)

(defcustom rmail-preserve-inbox nil
231
  "Non-nil means leave incoming mail in the user's inbox--don't delete it."
232 233 234 235
  :type 'boolean
  :group 'rmail-retrieve)

(defcustom rmail-movemail-search-path nil
236 237 238
  "List of directories to search for movemail (in addition to `exec-path')."
  :group 'rmail-retrieve
  :type '(repeat (directory)))
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

(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)
  "Determine what flavor of movemail PROG is.
We do this by executing it with `--version' and analyzing its output."
  (with-temp-buffer
    (let ((tbuf (current-buffer)))
      (buffer-disable-undo tbuf)
      (call-process prog nil tbuf nil "--version")
      (if (not (buffer-modified-p tbuf))
	  ;; Should not happen...
	  nil
	(goto-char (point-min))
	(cond
	 ((looking-at ".*movemail: invalid option")
	  'emacs)    ;; Possibly...
	 ((looking-at "movemail (GNU Mailutils .*)")
	  'mailutils)
	 (t
	  ;; FIXME:
	  'emacs))))))

(defun rmail-autodetect ()
  "Determine the file name of the `movemail' program and return its flavor.
If `rmail-movemail-program' is non-nil, use it.
Otherwise, look for `movemail' in the directories in
`rmail-movemail-search-path', those in `exec-path', and `exec-directory'."
  (if rmail-movemail-program
      (rmail-probe rmail-movemail-program)
    (catch 'scan
      (dolist (dir (append rmail-movemail-search-path exec-path
			   (list exec-directory)))
	(when (and dir (file-accessible-directory-p dir))
	  ;; Previously, this didn't have to work on Windows, because
	  ;; rmail-insert-inbox-text before r1.439 fell back to using
	  ;; (expand-file-name "movemail" exec-directory) and just
	  ;; assuming it would work.
	  ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-02/msg00087.html
	  (let ((progname (expand-file-name
			   (concat "movemail"
				   (if (memq system-type '(ms-dos windows-nt))
				       ".exe")) dir)))
	    (when (and (not (file-directory-p progname))
		       (file-executable-p progname))
	      (let ((x (rmail-probe progname)))
		(when x
		  (setq rmail-movemail-program progname)
		  (throw 'scan x))))))))))

(defvar rmail-movemail-variant-in-use nil
  "The movemail variant currently in use. Known variants are:

  `emacs'     Means any implementation, compatible with the native Emacs one.
              This is the default;
  `mailutils' Means GNU mailutils implementation, capable of handling full
mail URLs as the source mailbox.")

;;;###autoload
(defun rmail-movemail-variant-p (&rest variants)
  "Return t if the current movemail variant is any of VARIANTS.
Currently known variants are 'emacs and 'mailutils."
  (when (not rmail-movemail-variant-in-use)
    ;; Autodetect
    (setq rmail-movemail-variant-in-use (rmail-autodetect)))
  (not (null (member rmail-movemail-variant-in-use variants))))

;; Call for effect, to set rmail-movemail-program (if not set by the
;; user), and rmail-movemail-variant-in-use. Used by various functions.
;; I'm not sure if M-x rmail is the only entry point to this package.
;; If so, this can be moved there.
(rmail-movemail-variant-p)

;;;###autoload
316 317
(defcustom rmail-dont-reply-to-names nil
  "A regexp specifying addresses to prune from a reply message.
318 319 320 321 322 323
A value of nil means exclude your own email address as an address
plus whatever is specified by `rmail-default-dont-reply-to-names'."
  :type '(choice regexp (const :tag "Your Name" nil))
  :group 'rmail-reply)

;;;###autoload
324 325
(defvar rmail-default-dont-reply-to-names "\\`info-"
  "A regular expression specifying part of the default value of the
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
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.")

(defcustom rmail-ignored-headers
  (concat "^via:\\|^mail-from:\\|^origin:\\|^references:\\|^sender:"
	  "\\|^status:\\|^received:\\|^x400-originator:\\|^x400-recipients:"
	  "\\|^x400-received:\\|^x400-mts-identifier:\\|^x400-content-type:"
	  "\\|^\\(resent-\\|\\)message-id:\\|^summary-line:\\|^resent-date:"
	  "\\|^nntp-posting-host:\\|^path:\\|^x-char.*:\\|^x-face:\\|^face:"
	  "\\|^x-mailer:\\|^delivered-to:\\|^lines:"
	  "\\|^content-transfer-encoding:\\|^x-coding-system:"
	  "\\|^return-path:\\|^errors-to:\\|^return-receipt-to:"
	  "\\|^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:\\|^dkim-signature:"
	  "\\|^resent-face:\\|^resent-x.*:\\|^resent-organization:\\|^resent-openpgp:"
	  "\\|^x-.*:")
349
  "Regexp to match header fields that Rmail should normally hide.
350 351 352 353 354 355 356 357 358 359 360
\(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,
when you view the message for the first time in Rmail.
To make a change in this variable take effect
for a message that you have already viewed,
go to that message and type \\[rmail-toggle-header] twice."
  :type 'regexp
  :group 'rmail-headers)

(defcustom rmail-nonignored-headers "^x-spam-status:"
361
  "Regexp to match X header fields that Rmail should show.
362 363 364 365 366 367 368 369 370 371 372 373 374 375
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'.

This variable is used for reformatting the message header,
which normally happens once for each message,
when you view the message for the first time in Rmail.
To make a change in this variable take effect
for a message that you have already viewed,
go to that message and type \\[rmail-toggle-header] twice."
  :type '(choice (const nil) (regexp))
  :group 'rmail-headers)

(defcustom rmail-displayed-headers nil
376
  "Regexp to match Header fields that Rmail should display.
377 378 379 380 381
If nil, display all header fields except those matched by
`rmail-ignored-headers'."
  :type '(choice regexp (const :tag "All"))
  :group 'rmail-headers)

382 383
(defcustom rmail-retry-ignored-headers "^x-authentication-warning:"
  "Headers that should be stripped when retrying a failed message."
384 385 386
  :type '(choice regexp (const nil :tag "None"))
  :group 'rmail-headers)

387 388
(defcustom rmail-highlighted-headers "^From:\\|^Subject:"
  "Regexp to match Header fields that Rmail should normally highlight.
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
A value of nil means don't highlight."
  :type 'regexp
  :group 'rmail-headers)

(defface rmail-highlight
  '((t (:inherit highlight)))
  "Face to use for highlighting the most important header fields."
  :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."
  :group 'rmail-headers
  :version "23.1")

405 406
(defcustom rmail-delete-after-output nil
  "Non-nil means automatically delete a message that is copied to a file."
407 408 409 410
  :type 'boolean
  :group 'rmail-files)

;;;###autoload
411 412
(defcustom rmail-primary-inbox-list nil
  "List of files which are inboxes for user's primary mail file `~/RMAIL'.
413 414 415 416 417 418 419 420 421 422 423 424 425 426
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.
  :type (list 'choice '(const :tag "Default" nil)
	      (list 'repeat ':value (list (or (getenv "MAIL")
					      (concat "/var/spool/mail/"
						      (getenv "USER"))))
		    'file))
  :group 'rmail-retrieve
  :group 'rmail-files)

(defcustom rmail-mail-new-frame nil
427
  "Non-nil means Rmail makes a new frame for composing outgoing mail.
428 429 430 431 432 433 434
This is handy if you want to preserve the window configuration of
the frame where you have the RMAIL buffer displayed."
  :type 'boolean
  :group 'rmail-reply)

;;;###autoload
(defcustom rmail-secondary-file-directory "~/"
435
  "Directory for additional secondary Rmail files."
436 437 438 439
  :type 'directory
  :group 'rmail-files)
;;;###autoload
(defcustom rmail-secondary-file-regexp "\\.xmail$"
440
  "Regexp for which files are secondary Rmail files."
441 442 443 444
  :type 'regexp
  :group 'rmail-files)

(defcustom rmail-confirm-expunge 'y-or-n-p
445
  "Whether and how to ask for confirmation before expunging deleted messages."
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  :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)

;;;###autoload
(defvar rmail-mode-hook nil
  "List of functions to call when Rmail is invoked.")

(defvar rmail-get-new-mail-hook nil
  "List of functions to call when Rmail has retrieved new mail.")

;;;###autoload
(defcustom rmail-show-message-hook nil
  "List of functions to call when Rmail displays a message."
  :type 'hook
  :options '(goto-address)
  :group 'rmail)

(defvar rmail-quit-hook nil
  "List of functions to call when quitting out of Rmail.")

(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
still the current message in the Rmail buffer.")

;; These may be altered by site-init.el to match the format of mmdf files
;;  delimiting used on a given host (delim1 and delim2 from the config
;;  files).

(defvar rmail-mmdf-delim1 "^\001\001\001\001\n"
  "Regexp marking the start of an mmdf message.")
(defvar rmail-mmdf-delim2 "^\001\001\001\001\n"
  "Regexp marking the end of an mmdf message.")

(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,
before obeying `rmail-ignored-headers'."
  :group 'rmail-headers
  :type '(choice (const nil) function))

(defcustom rmail-automatic-folder-directives nil
  "List of directives specifying where to put a message.
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.

If FOLDERNAME is \"/dev/null\", it is deleted.
If FOLDERNAME is nil then it is deleted, and skipped.

FIELD is the plain text name of a field in the message, such as
\"subject\" or \"from\".  A FIELD of \"to\" will automatically include
all text from the \"cc\" field as well.

REGEXP is an expression to match in the preceeding specified FIELD.
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."
  :group 'rmail
  :version "21.1"
  :type '(repeat (sexp :tag "Directive")))

(defvar rmail-reply-prefix "Re: "
  "String to prepend to Subject line when replying to a message.")

;; Some mailers use "Re(2):" or "Re^2:" or "Re: Re:" or "Re[2]:".
;; This pattern should catch all the common variants.
;; rms: I deleted the change to delete tags in square brackets
;; because they mess up RT tags.
(defvar rmail-reply-regexp "\\`\\(Re\\(([0-9]+)\\|\\[[0-9]+\\]\\|\\^[0-9]+\\)?: *\\)*"
  "Regexp to delete from Subject line before inserting `rmail-reply-prefix'.")

(defcustom rmail-display-summary nil
527
  "If non-nil, Rmail always displays the summary buffer."
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
  :group 'rmail-summary
  :type 'boolean)

(defvar rmail-inbox-list nil)
(put 'rmail-inbox-list '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)

;; Message counters and markers.  Deleted flags.

(defvar rmail-current-message nil)
(put 'rmail-current-message 'permanent-local t)

(defvar rmail-total-messages nil)
(put 'rmail-total-messages 'permanent-local t)

(defvar rmail-message-vector nil)
(put 'rmail-message-vector 'permanent-local t)

(defvar rmail-deleted-vector nil)
(put 'rmail-deleted-vector 'permanent-local t)

(defvar rmail-msgref-vector nil
  "In an Rmail buffer, a vector whose Nth element is a list (N).
When expunging renumbers messages, these lists are modified
by substituting the new message number into the existing list.")
(put 'rmail-msgref-vector 'permanent-local t)

(defvar rmail-overlay-list nil)
(put 'rmail-overlay-list 'permanent-local t)

;; These are used by autoloaded rmail-summary.

(defvar rmail-summary-buffer nil)
(put 'rmail-summary-buffer 'permanent-local t)
(defvar rmail-summary-vector nil)
(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'.")
574
(make-variable-buffer-local 'rmail-buffer-swapped)
575
(put 'rmail-buffer-swapped 'permanent-local t)
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592

(defvar rmail-view-buffer nil
  "Buffer which holds RMAIL message for MIME displaying.")
(put 'rmail-view-buffer 'permanent-local t)

;; `Sticky' default variables.

;; Last individual label specified to a or k.
(defvar rmail-last-label nil)

;; 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)

(defvar rmail-last-regexp nil)
(put 'rmail-last-regexp 'permanent-local t)

(defcustom rmail-default-file "~/xmail"
593
  "Default file name for \\[rmail-output]."
594 595 596
  :type 'file
  :group 'rmail-files)
(defcustom rmail-default-body-file "~/mailout"
597
  "Default file name for \\[rmail-output-body-to-file]."
598 599 600 601 602 603 604 605 606 607 608 609 610
  :type 'file
  :group 'rmail-files
  :version "20.3")

;; Mule and MIME related variables.

;;;###autoload
(defvar rmail-file-coding-system nil
  "Coding system used in RMAIL file.

This is set to nil by default.")

(defcustom rmail-enable-mime nil
611
  "If non-nil, RMAIL uses MIME features.
612 613 614 615
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.

616 617
Even if the value is non-nil, you can't use MIME features
unless the feature specified by `rmail-mime-feature' is available."
618 619 620 621 622 623 624 625
  :type '(choice (const :tag "on" t)
		 (const :tag "off" nil)
		 (other :tag "when asked" ask))
  :group 'rmail)

(defvar rmail-enable-mime-composing nil
  "*If non-nil, RMAIL uses `rmail-insert-mime-forwarded-message-function' to forward.")

626
;; FIXME unused.
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
(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.
It is called with no argument.")

;;;###autoload
(defvar rmail-insert-mime-forwarded-message-function nil
  "Function to insert a message in MIME format so it can be forwarded.
This function is called if `rmail-enable-mime' or
`rmail-enable-mime-composing' 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.")

(defvar rmail-insert-mime-resent-message-function nil
  "Function to insert a message in MIME format so it can be resent.
643
This function is called by `rmail-resend' if `rmail-enable-mime' is non-nil.
644 645 646 647
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.")

648 649
;; FIXME one might want to pass a LIMIT, as per
;; rmail-search-mime-header-function.
650 651
(defvar rmail-search-mime-message-function nil
  "Function to check if a regexp matches a MIME message.
652 653 654
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
655 656 657 658
MSG is the message number, REGEXP is the regular expression.")

(defvar rmail-search-mime-header-function nil
  "Function to check if a regexp matches a header of MIME message.
659 660 661 662 663
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.")
664 665 666 667 668 669 670 671 672

(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,
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/>.")

673
;; FIXME this is unused.
674 675 676 677 678
(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.

679
If the variable `rmail-enable-mime' is non-nil, this variable is
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
ignored, and all the decoding work is done by a feature specified by
the variable `rmail-mime-feature'.")

(defvar rmail-mime-charset-pattern
  (concat "^content-type:[ \t]*text/plain;"
	  "\\(?:[ \t\n]*\\(?:format\\|delsp\\)=\"?[-a-z0-9]+\"?;\\)*"
	  "[ \t\n]*charset=\"?\\([^ \t\n\";]+\\)\"?")
  "Regexp to match MIME-charset specification in a header of message.
The first parenthesized expression should match the MIME-charset name.")


;;; 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\\)?"
		 "\\|[-+]?[0-9][0-9][0-9][0-9]"
		 "\\|"
		 "\\) *")))
    (concat
     "From "

     ;; Many things can happen to an RFC 822 mailbox before it is put into
     ;; a `From' line.  The leading phrase can be stripped, e.g.
     ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
     ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
     ;; can be removed, e.g.
     ;;		From: joe@y.z (Joe	K
     ;;			User)
     ;; can yield `From joe@y.z (Joe 	K Fri Mar 22 08:11:15 1996', and
     ;;		From: Joe User
     ;;			<joe@y.z>
     ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
     ;; The mailbox can be removed or be replaced by white space, e.g.
     ;;		From: "Joe User"{space}{tab}
     ;;			<joe@y.z>
     ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
     ;; where {space} and {tab} represent the Ascii space and tab characters.
     ;; We want to match the results of any of these manglings.
     ;; The following regexp rejects names whose first characters are
     ;; obviously bogus, but after that anything goes.
     "\\([^\0-\b\n-\r\^?].*\\)? "

     ;; The time the message was sent.
     "\\([^\0-\r \^?]+\\) +"				; day of the week
     "\\([^\0-\r \^?]+\\) +"				; month
     "\\([0-3]?[0-9]\\) +"				; day of month
     "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"	; time of day

     ;; Perhaps a time zone, specified by an abbreviation, or by a
     ;; numeric offset.
     time-zone-regexp

     ;; The year.
     " \\([0-9][0-9]+\\) *"

     ;; On some systems the time zone can appear after the year, too.
     time-zone-regexp

     ;; Old uucp cruft.
     "\\(remote from .*\\)?"

     "\n"))
  nil)

(defvar rmail-font-lock-keywords
  ;; These are all matched case-insensitively.
  (eval-when-compile
    (let* ((cite-chars "[>|}]")
	   (cite-prefix "a-z")
	   (cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
      (list '("^\\(From\\|Sender\\|Resent-From\\):"
	      . 'rmail-header-name)
	    '("^Reply-To:.*$" . 'rmail-header-name)
	    '("^Subject:" . 'rmail-header-name)
	    '("^X-Spam-Status:" . 'rmail-header-name)
	    '("^\\(To\\|Apparently-To\\|Cc\\|Newsgroups\\):"
	      . 'rmail-header-name)
	    ;; Use MATCH-ANCHORED to effectively anchor the regexp left side.
	    `(,cite-chars
	      (,(concat "\\=[ \t]*"
			"\\(\\(\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
			"\\(" cite-chars "[ \t]*\\)\\)+\\)"
			"\\(.*\\)")
	       (beginning-of-line) (end-of-line)
	       (1 font-lock-comment-delimiter-face nil t)
	       (5 font-lock-comment-face nil t)))
	    '("^\\(X-[a-z0-9-]+\\|In-reply-to\\|Date\\):.*\\(\n[ \t]+.*\\)*$"
	      . 'rmail-header-name))))
  "Additional expressions to highlight in Rmail mode.")

;; Perform BODY in the summary buffer
;; in such a way that its cursor is properly updated in its own window.
(defmacro rmail-select-summary (&rest body)
  `(let ((total rmail-total-messages))
     (if (rmail-summary-displayed)
	 (let ((window (selected-window)))
	   (save-excursion
	     (unwind-protect
		 (progn
		   (pop-to-buffer rmail-summary-buffer)
		   ;; rmail-total-messages is a buffer-local var
		   ;; in the rmail buffer.
		   ;; This way we make it available for the body
		   ;; even tho the rmail buffer is not current.
		   (let ((rmail-total-messages total))
		     ,@body))
	       (select-window window))))
       (save-excursion
	 (set-buffer rmail-summary-buffer)
	 (let ((rmail-total-messages total))
	   ,@body)))
     (rmail-maybe-display-summary)))

;;;; *** 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
isn't provided."
  (when rmail-enable-mime
    (condition-case err
	(require rmail-mime-feature)
      (error
       (display-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)
	: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.
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
that file, but does not copy any new mail into the file.
Interactively, if you supply a prefix argument, then you
have a chance to specify a file name with the minibuffer.

If `rmail-display-summary' is non-nil, make a summary for this RMAIL file."
  (interactive (if current-prefix-arg
		   (list (read-file-name "Run rmail on RMAIL file: "))))
  (rmail-require-mime-maybe)
  (let* ((file-name (expand-file-name (or file-name-arg rmail-file-name)))
	 ;; 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))
	 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)
	  (when (and (verify-visited-file-modtime existed)
		     (eq major-mode 'rmail-mode))
	    (rmail-set-message-counters)))
      ;; The mail file is either unchanged or not visited.  Visit it.
      (switch-to-buffer
       (let ((enable-local-variables nil))
	 (find-file-noselect file-name))))
    ;; Insure that the collection and view buffers are in sync and
    ;; insure 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"))
    (or (and existed (> (buffer-size) 0))
	(setq run-mail-hook t))
    ;; Insure 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
	;; Only get new mail when there is not a file name argument.
	(unless file-name-arg
	  (rmail-get-new-mail))
      (progn
	(set-buffer mail-buf)
	(rmail-show-message-maybe (rmail-first-unseen-message))
	(if rmail-display-summary (rmail-summary))
	(rmail-construct-io-menu)
	(if run-mail-hook
	    (run-hooks 'rmail-mode-hook))))))

(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.
  (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.  Fix the
	 ;; babyl file header and use unrmail to convert to mbox
	 ;; format.
	 (let ((buffer-read-only nil))
	   (insert "BABYL OPTIONS: -*- rmail -*-\n")
	   (rmail-convert-babyl-to-mbox)))
	((equal (point-min) (point-max))
	 (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))
	    (erase-buffer)
	    (insert-file-contents-literally new-file)
	    (rmail-mode-1)
	    (rmail-perm-variables)
	    (rmail-variables)
	    (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."
  (let ((content-type-header (mail-fetch-field "content-type"))
	separator)
    (save-excursion
      (setq separator (search-forward "\n\n")))
    (if (and content-type-header
	     (string-match rmail-mime-charset-pattern content-type-header))
	(substring content-type-header (match-beginning 1) (match-end 1))
      'undecided)))

;;; Set up Rmail mode keymaps

(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-maybe)
  (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)
  (define-key rmail-mode-map "\C-o"   'rmail-output-as-seen)
  (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 "\C-c\C-w"    'rmail-widen)
  (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)
  )

(define-key rmail-mode-map [menu-bar] (make-sparse-keymap))

(define-key rmail-mode-map [menu-bar classify]
  (cons "Classify" (make-sparse-keymap "Classify")))

(define-key rmail-mode-map [menu-bar classify input-menu]
  nil)

(define-key rmail-mode-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 rmail-mode-map [menu-bar classify output-inbox]
  '("Output..." . rmail-output))

(define-key rmail-mode-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 rmail-mode-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 rmail-mode-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 rmail-mode-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 rmail-mode-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 rmail-mode-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 rmail-mode-map [menu-bar mail lambda]
  '("----"))

(define-key rmail-mode-map [menu-bar mail continue]
  '("Continue" . rmail-continue))

(define-key rmail-mode-map [menu-bar mail resend]
  '("Re-send..." . rmail-resend))

(define-key rmail-mode-map [menu-bar mail forward]
  '("Forward" . rmail-forward))

(define-key rmail-mode-map [menu-bar mail retry]
  '("Retry" . rmail-retry-failure))

(define-key rmail-mode-map [menu-bar mail reply]
  '("Reply" . rmail-reply))

(define-key rmail-mode-map [menu-bar mail mail]
  '("Mail" . rmail-mail))

(define-key rmail-mode-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 rmail-mode-map [menu-bar delete expunge]
  '("Expunge" . rmail-expunge))

(define-key rmail-mode-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 rmail-mode-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 rmail-mode-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 rmail-mode-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 rmail-mode-map [menu-bar move first]
  '("First" . rmail-first-message))

(define-key rmail-mode-map [menu-bar move previous]
  '("Previous" . rmail-previous-message))

(define-key rmail-mode-map [menu-bar move next]
  '("Next" . rmail-next-message))

;; Rmail toolbar
(defvar rmail-tool-bar-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))



;; Rmail mode is suitable only for specially formatted data.
(put 'rmail-mode 'mode-class 'special)

(defun rmail-mode-kill-summary ()
  (if rmail-summary-buffer (kill-buffer rmail-summary-buffer)))

;;;###autoload
(defun rmail-mode ()
  "Rmail Mode is used by \\<rmail-mode-map>\\[rmail] for editing Rmail files.
All normal editing commands are turned off.
Instead, these commands are available:

\\[rmail-beginning-of-message]	Move point to front of this message.
\\[rmail-end-of-message]	Move point to bottom of this message.
\\[scroll-up]	Scroll to next screen of this message.
\\[scroll-down]	Scroll to previous screen of this message.
\\[rmail-next-undeleted-message]	Move to Next non-deleted message.
\\[rmail-previous-undeleted-message]	Move to Previous non-deleted message.
\\[rmail-next-message]	Move to Next message whether deleted or not.
\\[rmail-previous-message]	Move to Previous message whether deleted or not.
\\[rmail-first-message]	Move to the first message in Rmail file.
\\[rmail-last-message]	Move to the last message in Rmail file.
\\[rmail-show-message-maybe]	Jump to message specified by numeric position in file.
\\[rmail-search]	Search for string and show message it is found in.
\\[rmail-delete-forward]	Delete this message, move to next nondeleted.
\\[rmail-delete-backward]	Delete this message, move to previous nondeleted.
\\[rmail-undelete-previous-message]	Undelete message.  Tries current message, then earlier messages
	till a deleted message is found.
\\[rmail-edit-current-message]	Edit the current message.  \\[rmail-cease-edit] to return to Rmail.
\\[rmail-expunge]	Expunge deleted messages.
\\[rmail-expunge-and-save]	Expunge and save the file.
\\[rmail-quit]       Quit Rmail: expunge, save, then switch to another buffer.
\\[save-buffer] Save without expunging.
\\[rmail-get-new-mail]	Move new mail from system spool directory into this file.
\\[rmail-mail]	Mail a message (same as \\[mail-other-window]).
\\[rmail-continue]	Continue composing outgoing message started before.
\\[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]	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.
\\[rmail-kill-label]	Kill label.  Remove a label from current message.
\\[rmail-next-labeled-message]   Move to Next message with specified label
          (label defaults to last one specified).
          Standard labels: filed, unseen, answered, forwarded, deleted.
          Any other label is present only if you add it with \\[rmail-add-label].
\\[rmail-previous-labeled-message]   Move to Previous message with specified label
\\[rmail-summary]	Show headers buffer, with a one line summary of each message.
\\[rmail-summary-by-labels]	Summarize only messages with particular label(s).
\\[rmail-summary-by-recipients]   Summarize only messages with particular recipient(s).
\\[rmail-summary-by-regexp]   Summarize only messages with particular regexp(s).
\\[rmail-summary-by-topic]   Summarize only messages with subject line regexp(s).
\\[rmail-toggle-header]	Toggle display of complete header."
  (interactive)
  (let ((finding-rmail-file (not (eq major-mode 'rmail-mode))))
    (rmail-mode-2)
    (when (and finding-rmail-file
	       (null coding-system-for-read)
	       default-enable-multibyte-characters)
      (let ((rmail-enable-multibyte t))
	(rmail-require-mime-maybe)
	(rmail-convert-file-maybe)
	(goto-char (point-max))
	(set-buffer-multibyte t)))
    (rmail-set-message-counters)
    (rmail-show-message-maybe rmail-total-messages)
    (when finding-rmail-file
      (when rmail-display-summary
	(rmail-summary))
      (rmail-construct-io-menu))
    (run-mode-hooks 'rmail-mode-hook)))

(defun rmail-mode-2 ()
  (kill-all-local-variables)
  (rmail-mode-1)
  (rmail-perm-variables)
  (rmail-variables))

(defun rmail-mode-1 ()
  (setq major-mode 'rmail-mode)
  (setq mode-name "RMAIL")
  (setq buffer-read-only t)
  ;; 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 another mbox buffer.
  ;; rmail-output enables auto save when you do that.
  (setq buffer-auto-save-file-name nil)
  (use-local-map rmail-mode-map)
  (set-syntax-table text-mode-syntax-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)))
1269 1270
    (or buf
	(generate-new-buffer name))))
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773

(defun rmail-change-major-mode-hook ()
  ;; Bring the actual Rmail messages back into the main buffer.
  (when (rmail-buffers-swapped-p)
    (setq rmail-buffer-swapped nil)
    (let ((modp (buffer-modified-p)))
      (buffer-swap-text rmail-view-buffer)
      (set-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-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)
      (let ((modp (buffer-modified-p)))
	(buffer-swap-text rmail-view-buffer)
	(set-buffer-modified-p modp))
      (setq rmail-buffer-swapped nil))))

(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-regexp)
  (make-local-variable 'rmail-deleted-vector)
  (make-local-variable 'rmail-buffer)
  (setq rmail-buffer (current-buffer))
  (set-buffer-multibyte nil)
  (make-local-variable 'rmail-view-buffer)
  (save-excursion
    (setq rmail-view-buffer (rmail-generate-viewer-buffer))
    (set-buffer rmail-view-buffer)
    (setq buffer-undo-list t)
    (set-buffer-multibyte t))
  (make-local-variable 'rmail-summary-buffer)
  (make-local-variable 'rmail-summary-vector)
  (make-local-variable 'rmail-current-message)
  (make-local-variable 'rmail-total-messages)
  (setq rmail-total-messages 0)
  (make-local-variable 'rmail-overlay-list)
  (setq rmail-overlay-list nil)
  (make-local-variable 'rmail-message-vector)
  (make-local-variable 'rmail-msgref-vector)
  (make-local-variable 'rmail-inbox-list)
  ;; 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))
	   (equal buffer-file-truename
		  (abbreviate-file-name (file-truename rmail-file-name))))
       (setq rmail-inbox-list
	     (or rmail-primary-inbox-list
		 (list (or (getenv "MAIL")
			   (concat rmail-spool-directory
				   (user-login-name)))))))
  (set (make-local-variable 'tool-bar-map) rmail-tool-bar-map))

;; Set up the non-permanent locals associated with Rmail mode.
(defun rmail-variables ()
  ;; 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)
  (make-local-variable 'revert-buffer-function)
  (setq revert-buffer-function 'rmail-revert)
  (make-local-variable 'font-lock-defaults)
  (setq font-lock-defaults
	'(rmail-font-lock-keywords
	  t t nil nil
	  (font-lock-maximum-size . nil)
	  (font-lock-fontify-buffer-function . rmail-fontify-buffer-function)
	  (font-lock-unfontify-buffer-function . rmail-unfontify-buffer-function)
	  (font-lock-inhibit-thing-lock . (lazy-lock-mode fast-lock-mode))))
  (make-local-variable 'require-final-newline)
  (setq require-final-newline nil)
  (make-local-variable 'version-control)
  (setq version-control 'never)
  (make-local-variable 'kill-buffer-hook)
  (add-hook 'kill-buffer-hook 'rmail-mode-kill-summary)
  (make-local-variable 'file-precious-flag)
  (setq file-precious-flag t)
  (make-local-variable 'desktop-save-buffer)
  (setq desktop-save-buffer t))

;; 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)))
    ;; Call our caller again, but this time it does the default thing.
    (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-maybe rmail-total-messages)
      (run-hooks 'rmail-mode-hook))))

(defun rmail-expunge-and-save ()
  "Expunge and save RMAIL file."
  (interactive)
  (set-buffer rmail-buffer)
  (rmail-expunge t)
  (rmail-swap-buffers-maybe)
  (save-buffer)
  (if (rmail-summary-exists)
      (rmail-select-summary (set-buffer-modified-p nil))
    (rmail-show-message)))

(defun rmail-quit ()
  "Quit out of RMAIL.
Hook `rmail-quit-hook' is run after expunging."
  (interactive)
  (set-buffer rmail-buffer)
  (rmail-expunge t)
  (rmail-swap-buffers-maybe)
  (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
    (replace-buffer-in-windows rmail-summary-buffer)
    (bury-buffer rmail-summary-buffer))
  (if rmail-enable-mime
      (let ((obuf rmail-buffer)
	    (ovbuf rmail-view-buffer))
	(set-buffer rmail-view-buffer)
	(quit-window)
	(replace-buffer-in-windows ovbuf)
	(replace-buffer-in-windows obuf)
	(bury-buffer obuf))
    (let ((obuf (current-buffer)))
      (quit-window)
      (replace-buffer-in-windows obuf))))

(defun rmail-bury ()
  "Bury current Rmail buffer and its summary buffer."
  (interactive)
  ;; This let var was called rmail-buffer, but that interfered
  ;; with the buffer-local var used in summary buffers.
  (let ((buffer-to-bury (current-buffer)))
    (if (rmail-summary-exists)
	(let (window)
	  (while (setq window (get-buffer-window rmail-summary-buffer))
	    (quit-window nil window))
	  (bury-buffer rmail-summary-buffer)))
    (quit-window)))

(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-maybe number)
    (message "Message duplicated")))

;;;###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.
;; rms, Sep 1996.
(defun rmail-find-all-files (start)
  "Return list of file in dir START that match `rmail-secondary-file-regexp'."
  (if (file-accessible-directory-p start)
      ;; Don't sort here.
      (let* ((case-fold-search t)
	     (files (directory-files start t rmail-secondary-file-regexp)))
	;; Sort here instead of in directory-files
	;; because this list is usually much shorter.
	(sort files 'string<))))

(defun rmail-list-to-menu (menu-name l action &optional full-name)
  (let ((menu (make-sparse-keymap menu-name)))
    (mapc
     (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))

;; This command is always "disabled" when it appears in a menu.
(put 'rmail-disable-menu 'menu-enable ''nil)

(defun rmail-construct-io-menu ()
  (let ((files (rmail-find-all-files rmail-secondary-file-directory)))
    (if files
	(progn
	  (define-key rmail-mode-map [menu-bar classify input-menu]
	    (cons "Input Rmail File"
		  (rmail-list-to-menu "Input Rmail File"
				      files
				      'rmail-input)))
	  (define-key rmail-mode-map [menu-bar classify output-menu]
	    (cons "Output Rmail File"
		  (rmail-list-to-menu "Output Rmail File"
				      files
				      'rmail-output))))

      (define-key rmail-mode-map [menu-bar classify input-menu]
	'("Input Rmail File" . rmail-disable-menu))
      (define-key rmail-mode-map [menu-bar classify output-menu]
	'("Output Rmail File" . rmail-disable-menu)))))


;;;; *** 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))
(declare-function rfc822-addresses "rfc822" (header-text))
(declare-function mail-abbrev-make-syntax-table "mailabbrev.el" ())
(declare-function mail-sendmail-delimit-header "sendmail" ())
(declare-function mail-header-end "sendmail" ())

;; RLK feature not added in this version:
;; argument specifies inbox file or files in various ways.

(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.

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."
  (interactive
   (list (if current-prefix-arg
	     (read-file-name "Get new mail from file: "))))
  (run-hooks 'rmail-before-get-new-mail-hook)
  ;; If the disk file has been changed from under us,
  ;; revert to it before we get new mail.
  (or (verify-visited-file-modtime (current-buffer))
      (find-file (buffer-file-name)))
  (set-buffer rmail-buffer)
  (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))
	(rmail-enable-multibyte (default-value 'enable-multibyte-characters))
	found)
    (unwind-protect
	(when all-files
	  (let ((opoint (point))
		;; 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 while getting mail.
		(buffer-undo-list t)
		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.
	    (while (and all-files
			(not (member (file-name-nondirectory (car all-files))
				     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))
	    (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
	    (setq found (rmail-get-new-mail-1 file-name files delete-files))))
      found)
    ;; Don't leave the buffer screwed up if we get a disk-full error.
    (or found (rmail-show-message-maybe))))

(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)"))
	  ;; Generate the spam message.
	  (setq blurb (if spam-filter-p
			  (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)
	(when spam-filter-p
	  (if rsf-beep (beep t))
	  (sleep-for rsf-sleep-after-message))

	;; Establish the return value and move to the first new
	;; message unless we have other unseen messages before it.
	(setq result (> new-messages 0))
	(when result
	  (rmail-show-message-maybe (rmail-first-unseen-message)))
	(run-hooks 'rmail-after-get-new-mail-hook)
	result))))

(defun rmail-get-new-mail-filter-spam (new-message-count)
  "Process new messages for spam."
  (let* ((old-messages (- rmail-total-messages new-message-count))
	 (rsf-number-of-spam 0)
	 (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)))
	 blurb)
    ;; 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) ?\ )))
    ;; Generate a return value message based on the number of spam
    ;; messages found.
    (cond
     ((zerop rsf-number-of-spam) "")
     ((= 1 new-message-count) ", and appears to be spam")
     ((= rsf-number-of-spam new-message-count) ", 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"))))

(defun rmail-parse-url (file)
  "Parse the supplied URL. Return (list MAILBOX-NAME REMOTE PASSWORD GOT-PASSWORD)
WHERE MAILBOX-NAME is the name of the mailbox suitable as argument to the
actual version of `movemail', REMOTE is non-nil if MAILBOX-NAME refers to
a remote mailbox, PASSWORD is the password if it should be
supplied as a separate argument to `movemail' or nil otherwise, GOT-PASSWORD
is non-nil if the user has supplied the password interactively.
"
  (cond
   ((string-match "^\\([^:]+\\)://\\(\\([^:@]+\\)\\(:\\([^@]+\\)\\)?@\\)?.*" file)
      (let (got-password supplied-password
	    (proto (match-string 1 file))
	    (user  (match-string 3 file))
	    (pass  (match-string 5 file))
	    (host  (substring file (or (match-end 2)
				       (+ 3 (match-end 1))))))

	(if (not pass)
	    (when rmail-remote-password-required
	      (setq got-password (not (rmail-have-password)))
	      (setq supplied-password (rmail-get-remote-password
				       (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")
		(list (concat "po:" user ":" host)
		      t
		      (or pass supplied-password)
		      got-password)
	      (error "Emacs movemail does not support %s protocol" proto))
	  (list file
		(or (string-equal proto "pop") (string-equal proto "imap"))
		(or supplied-password pass)
		got-password))))

   ((string-match "^po:\\([^:]+\\)\\(:\\(.*\\)\\)?" file)
    (let (got-password supplied-password
          (proto "pop")
	  (user  (match-string 1 file))
	  (host  (match-string 3 file)))

      (when rmail-remote-password-required
	(setq got-password (not (rmail-have-password)))
	(setq supplied-password (rmail-get-remote-password nil)))

      (list file "pop" supplied-password got-password)))

   (t
    (list file nil nil nil))))

(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.)
  (or (memq (file-locked-p buffer-file-name) '(nil t))
      (error "RMAIL file %s is locked"
	     (file-name-nondirectory buffer-file-name)))
1774
  (let (file tofile delete-files movemail popmail got-password password)
1775 1776 1777 1778 1779 1780
    (while files
      ;; Handle remote mailbox names specially; don't expand as filenames
      ;; in case the userid contains a directory separator.
      (setq file (car files))
      (let ((url-data (rmail-parse-url file)))
	(setq file (nth 0 url-data))
1781
	(setq popmail (nth 1 url-data))
1782 1783 1784
	(setq password (nth 2 url-data))
	(setq got-password (nth 3 url-data)))

1785
      (if popmail
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
	  (setq renamep t)
	(setq file (file-truename
		    (substitute-in-file-name (expand-file-name file)))))
      (setq tofile (expand-file-name
		    ;; Generate name to move to from inbox name,
		    ;; in case of multiple inboxes that need moving.
		    (concat ".newmail-"
			    (file-name-nondirectory
			     (if (memq system-type '(windows-nt cygwin ms-dos))
				 ;; cannot have colons in file name
				 (replace-regexp-in-string ":" "-" file)
			       file)))
		    ;; Use the directory of this rmail file
		    ;; because it's a nuisance to use the homedir
		    ;; if that is on a full disk and this rmail
		    ;; file isn't.
		    (file-name-directory
		     (expand-file-name buffer-file-name))))
      ;; Always use movemail to rename the file,
      ;; since there can be mailboxes in various directories.
1806
      (when (not popmail)
1807 1808 1809 1810 1811
	;; 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))))
1812
      (cond (popmail
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
	     (message "Getting mail from the remote server ..."))
	    ((and (file-exists-p tofile)
		  (/= 0 (nth 7 (file-attributes tofile))))
	     (message "Getting mail from %s..." tofile))
	    ((and (file-exists-p file)
		  (/= 0 (nth 7 (file-attributes file))))
	     (message "Getting mail from %s..." file)))
      ;; Set TOFILE if have not already done so, and
      ;; rename or copy the file FILE to TOFILE if and as appropriate.
      (cond ((not renamep)
	     (setq tofile file))
1824
	    ((or (file-exists-p tofile) (and (not popmail)
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949