rmail.el 177 KB
Newer Older
1 2
;;; rmail.el --- main code of "RMAIL" mail reader for Emacs

3 4
;; Copyright (C) 1985-1988, 1993-1998, 2000-2013 Free Software
;; Foundation, Inc.
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

;; 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)
41
(require 'rfc2047)
42

43 44 45
(declare-function compilation--message->loc "compile" (cl-x) t)
(declare-function epa--find-coding-system-for-mime-charset "epa" (mime-charset))

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

75
(defconst rmail-resent-attr-index 7
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  "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 total-messages)
(defvar tool-bar-map)
Eli Zaretskii's avatar
Eli Zaretskii committed
97
(defvar mail-encode-mml)
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 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

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

(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)
143 144 145 146 147 148 149 150

;;;###autoload
(defcustom rmail-file-name (purecopy "~/RMAIL")
  "Name of user's primary mail file."
  :type 'string
  :group 'rmail
  :version "21.1")

151 152 153 154 155 156 157
;;;###autoload
(put 'rmail-spool-directory 'standard-value
     '((cond ((file-exists-p "/var/mail") "/var/mail/")
	     ((file-exists-p "/var/spool/mail") "/var/spool/mail/")
	     ((memq system-type '(hpux usg-unix-v irix)) "/usr/mail/")
	     (t "/usr/spool/mail/"))))

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
;;;###autoload
(defcustom rmail-spool-directory
  (purecopy
  (cond ((file-exists-p "/var/mail")
	 ;; SVR4 and recent BSD are said to use this.
	 ;; Rather than trying to know precisely which systems use it,
	 ;; let's assume this dir is never used for anything else.
	 "/var/mail/")
	;; Many GNU/Linux systems use this name.
	((file-exists-p "/var/spool/mail") "/var/spool/mail/")
	((memq system-type '(hpux usg-unix-v irix)) "/usr/mail/")
	(t "/usr/spool/mail/")))
  "Name of directory used by system mailer for delivering new mail.
Its name should end with a slash."
  :initialize 'custom-initialize-delay
  :type 'directory
  :group 'rmail)
175 176

;;;###autoload(custom-initialize-delay 'rmail-spool-directory nil)
177 178 179 180 181 182

(defcustom rmail-movemail-program nil
  "If non-nil, the file name of the `movemail' program."
  :group 'rmail-retrieve
  :type '(choice (const nil) string))

183 184
(define-obsolete-variable-alias 'rmail-pop-password
  'rmail-remote-password "22.1")
185 186

(defcustom rmail-remote-password nil
187
  "Password to use when reading mail from a remote server.
188 189 190 191 192 193
This setting is ignored for mailboxes whose URL already contains a password."
  :type '(choice (string :tag "Password")
		 (const :tag "Not Required" nil))
  :group 'rmail-retrieve
  :version "22.1")

194 195 196
(define-obsolete-variable-alias 'rmail-pop-password-required
  'rmail-remote-password-required "22.1")

197
(defcustom rmail-remote-password-required nil
198
  "Non-nil if a password is required when reading mail from a remote server."
199 200 201 202 203
  :type 'boolean
  :group 'rmail-retrieve
  :version "22.1")

(defcustom rmail-movemail-flags nil
204
  "List of flags to pass to movemail.
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
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
221
  "Non-nil means leave incoming mail in the user's inbox--don't delete it."
222 223 224 225
  :type 'boolean
  :group 'rmail-retrieve)

(defcustom rmail-movemail-search-path nil
226 227 228
  "List of directories to search for movemail (in addition to `exec-path')."
  :group 'rmail-retrieve
  :type '(repeat (directory)))
229

230
(declare-function mail-dont-reply-to "mail-utils" (destinations))
231
(declare-function rmail-update-summary "rmailsum" (&rest ignore))
232
(declare-function rmail-mime-toggle-hidden "rmailmm" ())
233 234 235 236 237 238 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

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

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
;;;###autoload
(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")

322
;;;###autoload
Glenn Morris's avatar
Glenn Morris committed
323 324
(define-obsolete-variable-alias 'rmail-dont-reply-to-names
  'mail-dont-reply-to-names "24.1")
325

Glenn Morris's avatar
Glenn Morris committed
326
;; Prior to 24.1, this used to contain "\\`info-".
327
;;;###autoload
328 329 330 331 332 333 334
(defvar rmail-default-dont-reply-to-names nil
  "Regexp specifying part of the default value of `mail-dont-reply-to-names'.
This is used when the user does not set `mail-dont-reply-to-names'
explicitly.")
;;;###autoload
(make-obsolete-variable 'rmail-default-dont-reply-to-names
                        'mail-dont-reply-to-names "24.1")
335

336
;;;###autoload
337
(defcustom rmail-ignored-headers
338
  (purecopy
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  (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:"
355
	  "\\|^x-.*:"))
356
  "Regexp to match header fields that Rmail should normally hide.
357 358 359 360 361 362 363 364 365 366 367
\(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:"
368
  "Regexp to match X header fields that Rmail should show.
369 370 371 372 373 374 375 376 377 378 379 380 381
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)

382
;;;###autoload
383
(defcustom rmail-displayed-headers nil
384
  "Regexp to match Header fields that Rmail should display.
385 386 387 388 389
If nil, display all header fields except those matched by
`rmail-ignored-headers'."
  :type '(choice regexp (const :tag "All"))
  :group 'rmail-headers)

390
;;;###autoload
391
(defcustom rmail-retry-ignored-headers (purecopy "^x-authentication-warning:\\|^x-detected-operating-system:\\|^x-spam[-a-z]*:\\|content-type:\\|content-transfer-encoding:\\|mime-version:\\|message-id:")
392
  "Headers that should be stripped when retrying a failed message."
393
  :type '(choice regexp (const nil :tag "None"))
394
  :group 'rmail-headers
395
  :version "23.2")	   ; added x-detected-operating-system, x-spam
396

397
;;;###autoload
398
(defcustom rmail-highlighted-headers (purecopy "^From:\\|^Subject:")
399
  "Regexp to match Header fields that Rmail should normally highlight.
400
A value of nil means don't highlight.  Uses the face `rmail-highlight'."
401 402 403 404 405
  :type 'regexp
  :group 'rmail-headers)

(defface rmail-highlight
  '((t (:inherit highlight)))
406 407
  "Face to use for highlighting the most important header fields.
The variable `rmail-highlighted-headers' specifies which headers."
408 409 410
  :group 'rmail-headers
  :version "22.1")

411 412 413 414 415 416 417 418 419 420 421 422 423 424
;; This was removed in Emacs 23.1 with no notification, an unnecessary
;; incompatible change.
(defcustom rmail-highlight-face 'rmail-highlight
  "Face used by Rmail for highlighting headers."
  ;; Note that nil doesn't actually mean use the default face, it
  ;; means use either bold or highlight. It's not worth fixing this
  ;; now that this is obsolete.
  :type '(choice (const :tag "Default" nil)
		 face)
  :group 'rmail-headers)
(make-obsolete-variable 'rmail-highlight-face
			"customize the face `rmail-highlight' instead."
			"23.2")

425 426
(defface rmail-header-name
  '((t (:inherit font-lock-function-name-face)))
427 428 429
  "Face to use for highlighting the header names.
The variable `rmail-font-lock-keywords' specifies which headers
get highlighted."
430 431 432
  :group 'rmail-headers
  :version "23.1")

433 434
(defcustom rmail-delete-after-output nil
  "Non-nil means automatically delete a message that is copied to a file."
435 436 437 438
  :type 'boolean
  :group 'rmail-files)

;;;###autoload
439
(defcustom rmail-primary-inbox-list nil
440 441 442 443 444 445 446
  "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.)
447 448
  :type (list 'choice '(const :tag "Default" nil)
	      (list 'repeat ':value (list (or (getenv "MAIL")
449 450
					      (concat rmail-spool-directory
						      (user-login-name))))
451 452 453 454 455
		    'file))
  :group 'rmail-retrieve
  :group 'rmail-files)

(defcustom rmail-mail-new-frame nil
456
  "Non-nil means Rmail makes a new frame for composing outgoing mail.
457 458 459 460 461 462
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
463
(defcustom rmail-secondary-file-directory (purecopy "~/")
464
  "Directory for additional secondary Rmail files."
465 466 467
  :type 'directory
  :group 'rmail-files)
;;;###autoload
468
(defcustom rmail-secondary-file-regexp (purecopy "\\.xmail$")
469
  "Regexp for which files are secondary Rmail files."
470 471 472 473
  :type 'regexp
  :group 'rmail-files)

(defcustom rmail-confirm-expunge 'y-or-n-p
474 475 476
  "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."
477 478 479 480 481
  :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)
482
(put 'rmail-confirm-expunge 'risky-local-variable t)
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

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

515 516 517 518 519 520 521
;; 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).
522
;; See http://lists.gnu.org/archive/html/emacs-devel/2009-03/msg00013.html
523 524 525 526 527 528 529
(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))

530 531 532 533
(make-obsolete-variable 'rmail-message-filter
			"it is not used (try `rmail-show-message-hook')."
			"23.1")

534
(defcustom rmail-automatic-folder-directives nil
535 536 537 538 539 540
  "List of directives specifying how to automatically file messages.
Whenever Rmail shows a message in the folder that `rmail-file-name'
specifies, it calls `rmail-auto-file' to maybe file the message in
another folder according to this list.  Messages that are already
marked as `filed', or are in different folders, are left alone.

541 542 543 544
Each element of the list is of the form:

  (FOLDERNAME FIELD REGEXP [ FIELD REGEXP ] ... )

545 546 547 548
FOLDERNAME is the name of a folder in which to put the message.
If FOLDERNAME is nil then Rmail deletes the message, and moves on to
the next.  If FOLDERNAME is \"/dev/null\", Rmail deletes the message,
but does not move to the next.
549

550 551 552
FIELD is the name of a header field in the message, such as
\"subject\" or \"from\".  A FIELD of \"to\" includes all text
from both the \"to\" and \"cc\" headers.
553

554 555
REGEXP is a regular expression to match (case-sensitively) against
the preceding specified FIELD.
556

557 558 559
There may be any number of FIELD/REGEXP pairs.
All pairs must match for a directive to apply to a message.
For a given message, Rmail applies only the first matching directive.
560

561
Examples:
562
  (\"/dev/null\" \"from\" \"@spam.com\") ; delete all mail from spam.com
563
  (\"RMS\" \"from\" \"rms@\") ; save all mail from RMS.
564
"
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
  :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
580
  "If non-nil, Rmail always displays the summary buffer."
581 582 583 584 585 586 587 588 589 590 591 592
  :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)

593 594 595 596 597 598 599 600
(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)

601 602
;; Message counters and markers.  Deleted flags.

603
(defvar rmail-current-message nil
604 605 606
  "Integer specifying the message currently being displayed in this folder.
Counts messages from 1 to `rmail-total-messages'.  A value of 0
means there are no messages in the folder.")
607 608
(put 'rmail-current-message 'permanent-local t)

609 610 611
(defvar rmail-total-messages nil
  "Integer specifying the total number of messages in this folder.
Includes deleted messages.")
612 613
(put 'rmail-total-messages 'permanent-local t)

614 615 616
(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.")
617 618
(put 'rmail-message-vector 'permanent-local t)

619 620 621 622
(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.")
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
(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)
638 639 640
(defvar rmail-summary-vector nil
  "In an Rmail buffer, vector of (newline-terminated) strings.
Element N specifies the summary line for message N+1.")
641 642 643 644 645 646
(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'.")
647
(make-variable-buffer-local 'rmail-buffer-swapped)
648
(put 'rmail-buffer-swapped 'permanent-local t)
649 650 651

(defvar rmail-view-buffer nil
  "Buffer which holds RMAIL message for MIME displaying.")
652
(make-variable-buffer-local 'rmail-view-buffer)
653 654 655 656 657 658 659 660 661 662 663 664 665
(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)

666
;; Note that rmail-output-read-file-name modifies this.
667
(defcustom rmail-default-file "~/xmail"
668
  "Default file name for \\[rmail-output]."
669 670 671
  :type 'file
  :group 'rmail-files)
(defcustom rmail-default-body-file "~/mailout"
672
  "Default file name for \\[rmail-output-body-to-file]."
673 674 675 676 677 678 679 680 681 682 683 684
  :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.")

Kenichi Handa's avatar
Kenichi Handa committed
685
(defcustom rmail-enable-mime t
686 687 688 689
  "If non-nil, RMAIL automatically displays decoded MIME messages.
For this to work, the feature specified by `rmail-mime-feature' must
be available."
  :type 'boolean
Kenichi Handa's avatar
Kenichi Handa committed
690
  :version "23.3"
691 692
  :group 'rmail)

Glenn Morris's avatar
Glenn Morris committed
693 694 695 696 697
(defcustom rmail-enable-mime-composing t
  "If non-nil, use `rmail-insert-mime-forwarded-message-function' to forward."
  :type 'boolean
  :version "24.1"			; nil -> t
  :group 'rmail)
698 699

(defvar rmail-show-mime-function nil
700
  "Function of no argument called to show a decoded MIME message.
701
This function is called when `rmail-enable-mime' is non-nil.
702
The package providing MIME support should set this.")
703 704 705 706

;;;###autoload
(defvar rmail-insert-mime-forwarded-message-function nil
  "Function to insert a message in MIME format so it can be forwarded.
Glenn Morris's avatar
Glenn Morris committed
707 708
This function is called if `rmail-enable-mime' and
`rmail-enable-mime-composing' are non-nil.
709 710 711 712 713 714
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.
715
This function is called by `rmail-resend' if `rmail-enable-mime' is non-nil.
716 717 718 719
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.")

720 721
;; FIXME one might want to pass a LIMIT, as per
;; rmail-search-mime-header-function.
722 723
(defvar rmail-search-mime-message-function nil
  "Function to check if a regexp matches a MIME message.
724 725 726
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
727 728 729 730
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.
731 732 733 734 735
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.")
736

Kenichi Handa's avatar
Kenichi Handa committed
737
(defvar rmail-mime-feature 'rmailmm
738
  "Feature to require for MIME support in Rmail.
Glenn Morris's avatar
Glenn Morris committed
739 740
When starting Rmail, if `rmail-enable-mime' is non-nil, this
feature is loaded with `require'.  The default value is `rmailmm'.
741

Glenn Morris's avatar
Glenn Morris committed
742 743 744 745 746 747
The library should set the variable `rmail-show-mime-function'
to an appropriate value, and optionally also set
`rmail-search-mime-message-function',
`rmail-search-mime-header-function',
`rmail-insert-mime-forwarded-message-function', and
`rmail-insert-mime-resent-message-function'.")
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

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


(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"))
807 808
  "Regexp matching the delimiter of messages in UNIX mail format
\(UNIX From lines), minus the initial ^.  Note that if you change
809
this expression, you must change the code in `rmail-nuke-pinhead-header'
810
that knows the exact ordering of the \\( \\) subexpressions.")
811

812 813 814
;; 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.
815 816 817 818
(defvar rmail-font-lock-keywords
  ;; These are all matched case-insensitively.
  (eval-when-compile
    (let* ((cite-chars "[>|}]")
819
	   (cite-prefix "[:alpha:]")
820 821 822
	   (cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
      (list '("^\\(From\\|Sender\\|Resent-From\\):"
	      . 'rmail-header-name)
823 824
	    '("^\\(Mail-\\)?Reply-To:.*$" . 'rmail-header-name)
	    ;; FIXME Mail-Followup-To should probably be here too.
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
	    '("^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.")

842 843 844 845 846 847
;; Rmail does not expect horizontal splitting.  (Bug#2282)
(defun rmail-pop-to-buffer (&rest args)
  "Like `pop-to-buffer', but with `split-width-threshold' set to nil."
  (let (split-width-threshold)
    (apply 'pop-to-buffer args)))

848 849 850 851 852 853 854 855 856
;; 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
857
		   (rmail-pop-to-buffer rmail-summary-buffer)
858 859 860 861 862 863 864
		   ;; 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))))
865
       (with-current-buffer rmail-summary-buffer
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
	 (let ((rmail-total-messages total))
	   ,@body)))
     (rmail-maybe-display-summary)))

;;;; *** Rmail Mode ***

(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
883
through `rmail-enable-mime' being non-nil, the required feature
884 885
`%s' (the value of `rmail-mime-feature')
is not available in the current session.
886
So, MIME support is turned off for the moment."
887 888 889 890 891 892 893 894
		rmail-mime-feature)
	:warning)
       (setq rmail-enable-mime nil)))))


;;;###autoload
(defun rmail (&optional file-name-arg)
  "Read and edit incoming mail.
895 896
Moves messages into file named by `rmail-file-name' and edits that
file in RMAIL Mode.
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
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))
922
	    (rmail-swap-buffers-maybe)
923 924 925
	    (rmail-set-message-counters)))
      ;; The mail file is either unchanged or not visited.  Visit it.
      (switch-to-buffer
926 927 928 929 930 931
       (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)))
932
	 (find-file-noselect file-name))))
933 934
    ;; Ensure that the collection and view buffers are in sync and
    ;; ensure that a message is not being edited.
935 936 937 938 939 940
    (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))
941
    ;; Ensure that the Rmail file is in mbox format, the buffer is in
942 943 944 945 946 947 948 949 950 951 952 953
    ;; 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
954
	  (setq msg-shown (rmail-get-new-mail)))
955 956
      (progn
	(set-buffer mail-buf)
957 958
	(or msg-shown
	    (rmail-show-message (rmail-first-unseen-message)))
959 960 961 962 963 964 965 966 967 968
	(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.
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
  (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.  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")))))
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003

(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...")
1004
	  (let ((inhibit-read-only t)
1005 1006
		(coding-system-for-read 'raw-text)
		(buffer-undo-list t))
1007
	    (erase-buffer)
1008
	    (insert-file-contents new-file)
1009 1010 1011
	    ;; 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)
1012 1013 1014
	    (rmail-mode-1)
	    (rmail-perm-variables)
	    (rmail-variables)
1015
	    (setq rmail-was-converted t)
1016
	    (rmail-dont-modify-format)
1017 1018 1019 1020 1021 1022 1023 1024 1025
	    (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."
1026 1027
  (save-excursion
    (goto-char (point-min))
1028
    (if (re-search-forward rmail-mime-charset-pattern nil t)
1029
	(coding-system-from-name (match-string 1))
1030 1031 1032 1033
      'undecided)))

;;; Set up Rmail mode keymaps

1034 1035 1036 1037 1038 1039 1040 1041 1042
(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)
1043
    ;; If you change this, change the rmail-resend menu-item's :keys.
1044 1045 1046 1047
    (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)
1048
    (define-key map "j"      'rmail-show-message)
1049 1050 1051 1052 1053 1054
    (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)
1055
    (define-key map "\e\C-f" 'rmail-summary-by-senders)
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    (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)
1075
    (define-key map "v"      'rmail-mime)
1076 1077 1078 1079 1080 1081 1082
    (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)
1083 1084
    (define-key map " "      'scroll-up-command)
    (define-key map "\177"   'scroll-down-command)
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    (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)

1096

1097 1098 1099 1100
    (define-key map [menu-bar] (make-sparse-keymap))

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

1102 1103
    (define-key map [menu-bar classify input-menu]
      nil)
1104

1105 1106
    (define-key map [menu-bar classify output-menu]
      nil)
1107

1108 1109
    (define-key map [menu-bar classify output-body]
      '("Output body to file..." . rmail-output-body-to-file))
1110

1111 1112
    (define-key map [menu-bar classify output-inbox]
      '("Output..." . rmail-output))
1113

1114 1115
    (define-key map [menu-bar classify output]
      '("Output as seen..." . rmail-output-as-seen))
1116

1117 1118
    (define-key map [menu-bar classify kill-label]
      '("Kill Label..." . rmail-kill-label))
1119

1120 1121
    (define-key map [menu-bar classify add-label]
      '("Add Label..." . rmail-add-label))
1122

1123 1124
    (define-key map [menu-bar summary]
      (cons "Summary" (make-sparse-keymap "Summary")))
1125

1126 1127
    (define-key map [menu-bar summary senders]
      '("By Senders..." . rmail-summary-by-senders))
1128

1129 1130
    (define-key map [menu-bar summary labels]
      '("By Labels..." . rmail-summary-by-labels))
1131

1132 1133
    (define-key map [menu-bar summary recipients]
      '("By Recipients..." . rmail-summary-by-recipients))
1134

1135 1136
    (define-key map [menu-bar summary topic]
      '("By Topic..." . rmail-summary-by-topic))
1137

1138 1139
    (define-key map [menu-bar summary regexp]
      '("By Regexp..." . rmail-summary-by-regexp))
1140

1141 1142
    (define-key map [menu-bar summary all]
      '("All" . rmail-summary))
1143

1144 1145
    (define-key map [menu-bar mail]
      (cons "Mail" (make-sparse-keymap "Mail")))
1146

1147 1148
    (define-key map [menu-bar mail rmail-get-new-mail]
      '("Get New Mail" . rmail-get-new-mail))
1149

1150 1151
    (define-key map [menu-bar mail lambda]
      '("----"))
1152

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

1156
    (define-key map [menu-bar mail resend]
1157
    '(menu-item "Resend..." rmail-resend :keys "C-u f"))
1158

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

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

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

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

1171 1172
    (define-key map [menu-bar delete]
      (cons "Delete" (make-sparse-keymap "Delete")))
1173

1174 1175
    (define-key map [menu-bar delete expunge/save]
      '("Expunge/Save" . rmail-expunge-and-save))
1176

1177 1178
    (define-key map [menu-bar delete expunge]
      '("Expunge" . rmail-expunge))
1179

1180 1181
    (define-key map [menu-bar delete undelete]
      '("Undelete" . rmail-undelete-previous-message))
1182

1183 1184
    (define-key map [menu-bar delete delete]
      '("Delete" . rmail-delete-forward))
1185

1186 1187
    (define-key map [menu-bar move]
      (cons "Move" (make-sparse-keymap "Move")))
1188

1189 1190
    (define-key map [menu-bar move search-back]
      '("Search Back..." . rmail-search-backwards))
1191

1192 1193
    (define-key map [menu-bar move search]
      '("Search..." . rmail-search))
1194

1195 1196
    (define-key map [menu-bar move previous]
      '("Previous Nondeleted" . rmail-previous-undeleted-message))
1197

1198 1199
    (define-key map [menu-bar move next]
      '("Next Nondeleted" . rmail-next-undeleted-message))
1200

1201 1202
    (define-key map [menu-bar move last]
      '("Last" . rmail-last-message))
1203

1204 1205
    (define-key map [menu-bar move first]
      '("First" . rmail-first-message))
1206

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

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

1213 1214
   map)
  "Keymap used in Rmail mode.")
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

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

1253 1254
(defvar rmail-enable-multibyte)         ; dynamically bound

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
;;;###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.
1271
\\[rmail-show-message]	Jump to message specified by numeric position in file.
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
\\[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)
1310
	       (default-value 'enable-multibyte-characters))
1311 1312 1313 1314 1315 1316
      (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)
1317
    (rmail-show-message rmail-total-messages)
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
    (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."
1352 1353 1354 1355 1356 1357
  ;; We want to reuse any existing view buffer, so as not to create an
  ;; endless number of them.  But we must avoid clashes if we visit
  ;; two different rmail files with the same basename (Bug#4593).
  (if (and (local-variable-p 'rmail-view-buffer)
	   (buffer-live-p rmail-view-buffer))
      rmail-view-buffer
1358 1359 1360 1361 1362 1363 1364 1365
    (let ((newbuf
	   (generate-new-buffer
	    (format " *message-viewer %s*"
		    (file-name-nondirectory
		     (or buffer-file-name (buffer-name)))))))
      (with-current-buffer newbuf
	(add-hook 'kill-buffer-hook 'rmail-view-buffer-kill-buffer-hook nil t))
      newbuf)))
1366

1367 1368 1369 1370 1371
(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'."
1372 1373 1374 1375 1376
  (let ((modp-this (buffer-modified-p))
	(modp-that
	 (with-current-buffer rmail-view-buffer (buffer-modified-p)))
	(coding-this buffer-file-coding-system)
	(coding-that
1377 1378 1379
	 (with-current-buffer rmail-view-buffer
	   buffer-file-coding-system)))
    (buffer-swap-text rmail-view-buffer)
1380 1381 1382 1383 1384
    (setq buffer-file-coding-system coding-that)
    (with-current-buffer rmail-view-buffer
      (setq buffer-file-coding-system coding-this)
      (restore-buffer-modified-p modp-that))
    (restore-buffer-modified-p modp-this)))