1;;; rmail.el --- main code of "RMAIL" mail reader for Emacs  -*- lexical-binding:t -*-
2
3;; Copyright (C) 1985-1988, 1993-1998, 2000-2021 Free Software
4;; Foundation, Inc.
5
6;; Maintainer: emacs-devel@gnu.org
7;; Keywords: mail
8
9;; This file is part of GNU Emacs.
10
11;; GNU Emacs is free software: you can redistribute it and/or modify
12;; it under the terms of the GNU General Public License as published by
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
15
16;; GNU Emacs is distributed in the hope that it will be useful,
17;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19;; GNU General Public License for more details.
20
21;; You should have received a copy of the GNU General Public License
22;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
23
24;;; Commentary:
25
26;;; Code:
27
28;; Souped up by shane@mit-ajax based on ideas of rlk@athena.mit.edu
29;;   New features include attribute and keyword support, message
30;;   selection by dispatch table, summary by attributes and keywords,
31;;   expunging by dispatch table, sticky options for file commands.
32
33;; Extended by Bob Weiner of Motorola
34;;   New features include: rmail and rmail-summary buffers remain
35;;   synchronized and key bindings basically operate the same way in both
36;;   buffers, summary by topic or by regular expression, rmail-reply-prefix
37;;   variable, and a bury rmail buffer (wipe) command.
38;;
39
40(require 'mail-utils)
41(require 'rfc2047)
42(require 'auth-source)
43
44(declare-function compilation--message->loc "compile" (cl-x) t)
45(declare-function epa--find-coding-system-for-mime-charset "epa" (mime-charset))
46
47(defconst rmail-attribute-header "X-RMAIL-ATTRIBUTES"
48  "The header that stores the Rmail attribute data.")
49
50(defconst rmail-keyword-header "X-RMAIL-KEYWORDS"
51  "The header that stores the Rmail keyword data.")
52
53;;; Attribute indexes
54
55(defconst rmail-answered-attr-index 0
56  "The index for the `answered' attribute.")
57
58(defconst rmail-deleted-attr-index 1
59  "The index for the `deleted' attribute.")
60
61(defconst rmail-edited-attr-index 2
62  "The index for the `edited' attribute.")
63
64(defconst rmail-filed-attr-index 3
65  "The index for the `filed' attribute.")
66
67(defconst rmail-retried-attr-index 4
68  "The index for the `retried' attribute.")
69
70(defconst rmail-forwarded-attr-index 5
71  "The index for the `forwarded' attribute.")
72
73(defconst rmail-unseen-attr-index 6
74  "The index for the `unseen' attribute.")
75
76(defconst rmail-resent-attr-index 7
77  "The index for the `resent' attribute.")
78
79(defconst rmail-attr-array
80  '[(?A "answered")
81    (?D "deleted")
82    (?E "edited")
83    (?F "filed")
84    (?R "retried")
85    (?S "forwarded")
86    (?U "unseen")
87    (?r "resent")]
88  "An array that provides a mapping between an attribute index,
89its character representation and its display representation.")
90
91(defvar deleted-head)
92(defvar font-lock-fontified)
93(defvar mail-abbrev-syntax-table)
94(defvar mail-abbrevs)
95(defvar messages-head)
96(defvar total-messages)
97(defvar tool-bar-map)
98(defvar mail-encode-mml)
99
100(defvar rmail-header-style 'normal
101  "The current header display style choice, one of
102`normal' (selected headers) or `full' (all headers).")
103
104(defvar rmail-mime-decoded nil
105  "Non-nil if message has been processed by `rmail-show-mime-function'.")
106(put 'rmail-mime-decoded 'permanent-local t) ; for rmail-edit
107
108(defsubst rmail-mime-message-p ()
109  "Non-nil if and only if the current message is a MIME."
110  (or (get-text-property (point) 'rmail-mime-entity)
111      (get-text-property (point-min) 'rmail-mime-entity)))
112
113(defgroup rmail nil
114  "Mail reader for Emacs."
115  :group 'mail)
116
117(defgroup rmail-retrieve nil
118  "Rmail retrieval options."
119  :prefix "rmail-"
120  :group 'rmail)
121
122(defgroup rmail-files nil
123  "Rmail files."
124  :prefix "rmail-"
125  :group 'rmail)
126
127(defgroup rmail-headers nil
128  "Rmail header options."
129  :prefix "rmail-"
130  :group 'rmail)
131
132(defgroup rmail-reply nil
133  "Rmail reply options."
134  :prefix "rmail-"
135  :group 'rmail)
136
137(defgroup rmail-summary nil
138  "Rmail summary options."
139  :prefix "rmail-"
140  :prefix "rmail-summary-"
141  :group 'rmail)
142
143(defgroup rmail-output nil
144  "Output message to a file."
145  :prefix "rmail-output-"
146  :prefix "rmail-"
147  :group 'rmail)
148
149(defgroup rmail-edit nil
150  "Rmail editing."
151  :prefix "rmail-edit-"
152  :group 'rmail)
153
154;;;###autoload
155(defcustom rmail-file-name (purecopy "~/RMAIL")
156  "Name of user's primary mail file."
157  :type 'string
158  :group 'rmail
159  :version "21.1")
160
161;;;###autoload
162(defcustom rmail-spool-directory
163  (purecopy
164  (cond ((file-exists-p "/var/mail")
165	 ;; SVR4 and recent BSD are said to use this.
166	 ;; Rather than trying to know precisely which systems use it,
167	 ;; let's assume this dir is never used for anything else.
168	 "/var/mail/")
169	;; Many GNU/Linux systems use this name.
170	((file-exists-p "/var/spool/mail") "/var/spool/mail/")
171	((memq system-type '(hpux usg-unix-v)) "/usr/mail/")
172	(t "/usr/spool/mail/")))
173  "Name of directory used by system mailer for delivering new mail.
174Its name should end with a slash."
175  :initialize #'custom-initialize-delay
176  :type 'directory
177  :group 'rmail)
178
179(defcustom rmail-movemail-program nil
180  "If non-nil, the file name of the `movemail' program."
181  :group 'rmail-retrieve
182  :type '(choice (const nil) string))
183
184(defcustom rmail-remote-password nil
185  "Password to use when reading mail from a remote server.
186This setting is ignored for mailboxes whose URL already contains a password."
187  :type '(choice (string :tag "Password")
188		 (const :tag "Not Required" nil))
189  :group 'rmail-retrieve
190  :version "22.1")
191
192(defcustom rmail-remote-password-required nil
193  "Non-nil if a password is required when reading mail from a remote server."
194  :type 'boolean
195  :group 'rmail-retrieve
196  :version "22.1")
197
198(defcustom rmail-movemail-flags nil
199  "List of flags to pass to movemail.
200Most commonly used to specify `-g' to enable GSS-API authentication
201or `-k' to enable Kerberos authentication."
202  :type '(repeat string)
203  :group 'rmail-retrieve
204  :version "20.3")
205
206(defvar rmail-remote-password-error "invalid usercode or password\\|
207unknown user name or bad password\\|Authentication failed\\|MU_ERR_AUTH_FAILURE"
208  "Regexp matching incorrect-password POP or IMAP server error messages.
209If you get an incorrect-password error that this expression does not match,
210please report it with \\[report-emacs-bug].")
211
212(defvar rmail-encoded-remote-password nil)
213
214(defcustom rmail-preserve-inbox nil
215  "Non-nil means leave incoming mail in the user's inbox--don't delete it."
216  :type 'boolean
217  :group 'rmail-retrieve)
218
219(defcustom rmail-movemail-search-path nil
220  "List of directories to search for movemail (in addition to `exec-path')."
221  :group 'rmail-retrieve
222  :type '(repeat (directory)))
223
224(declare-function mail-dont-reply-to "mail-utils" (destinations))
225(declare-function rmail-update-summary "rmailsum" (&rest ignore))
226(declare-function rmail-mime-toggle-hidden "rmailmm" ())
227(declare-function rmail-mime-entity-truncated "rmailmm" (entity))
228
229(defun rmail-probe (prog)
230  "Determine what flavor of movemail PROG is.
231We do this by executing it with `--version' and analyzing its output."
232  (with-temp-buffer
233    (let ((tbuf (current-buffer)))
234      (buffer-disable-undo tbuf)
235      (call-process prog nil tbuf nil "--version")
236      (if (not (buffer-modified-p tbuf))
237	  ;; Should not happen...
238	  nil
239	(goto-char (point-min))
240	(cond
241	 ((looking-at ".*movemail: invalid option")
242	  'emacs)    ;; Possibly...
243	 ((looking-at "movemail (GNU Mailutils")
244	  'mailutils)
245	 (t
246	  ;; FIXME:
247	  'emacs))))))
248
249(defun rmail-autodetect ()
250  "Determine the file name of the `movemail' program and return its flavor.
251If `rmail-movemail-program' is non-nil, use it.
252Otherwise, look for `movemail' in the directories in
253`rmail-movemail-search-path', those in `exec-path', and `exec-directory'."
254  (if rmail-movemail-program
255      (rmail-probe rmail-movemail-program)
256    (catch 'scan
257      (dolist (dir (append rmail-movemail-search-path exec-path
258			   (list exec-directory)))
259	(when (and dir (file-accessible-directory-p dir))
260	  ;; Previously, this didn't have to work on Windows, because
261	  ;; rmail-insert-inbox-text before r1.439 fell back to using
262	  ;; (expand-file-name "movemail" exec-directory) and just
263	  ;; assuming it would work.
264	  ;; https://lists.gnu.org/r/bug-gnu-emacs/2008-02/msg00087.html
265	  (let ((progname (expand-file-name
266			   (concat "movemail"
267				   (if (memq system-type '(ms-dos windows-nt))
268				       ".exe")) dir)))
269	    (when (and (not (file-directory-p progname))
270		       (file-executable-p progname))
271	      (let ((x (rmail-probe progname)))
272		(when x
273		  (setq rmail-movemail-program progname)
274		  (throw 'scan x))))))))))
275
276(defvar rmail-movemail-variant-in-use nil
277  "The movemail variant currently in use.  Known variants are:
278
279  `emacs'     Means any implementation, compatible with the native Emacs one.
280              This is the default;
281  `mailutils' Means GNU mailutils implementation, capable of handling full
282mail URLs as the source mailbox.")
283
284;;;###autoload
285(defun rmail-movemail-variant-p (&rest variants)
286  "Return t if the current movemail variant is any of VARIANTS.
287Currently known variants are `emacs' and `mailutils'."
288  (when (not rmail-movemail-variant-in-use)
289    ;; Autodetect
290    (setq rmail-movemail-variant-in-use (rmail-autodetect)))
291  (not (null (member rmail-movemail-variant-in-use variants))))
292
293;; Call for effect, to set rmail-movemail-program (if not set by the
294;; user), and rmail-movemail-variant-in-use. Used by various functions.
295;; I'm not sure if M-x rmail is the only entry point to this package.
296;; If so, this can be moved there.
297(rmail-movemail-variant-p)
298
299;;;###autoload
300(defcustom rmail-user-mail-address-regexp nil
301  "Regexp matching user mail addresses.
302If non-nil, this variable is used to identify the correspondent
303when receiving new mail.  If it matches the address of the sender,
304the recipient is taken as correspondent of a mail.
305If nil \(default value), your `user-login-name' and `user-mail-address'
306are used to exclude yourself as correspondent.
307
308Usually you don't have to set this variable, except if you collect mails
309sent by you under different user names.
310Then it should be a regexp matching your mail addresses.
311
312Setting this variable has an effect only before reading a mail."
313  :type '(choice (const :tag "None" nil) regexp)
314  :group 'rmail-retrieve
315  :version "21.1")
316
317;;;###autoload
318(define-obsolete-variable-alias 'rmail-dont-reply-to-names
319  'mail-dont-reply-to-names "24.1")
320
321;; Prior to 24.1, this used to contain "\\`info-".
322;;;###autoload
323(defvar rmail-default-dont-reply-to-names nil
324  "Regexp specifying part of the default value of `mail-dont-reply-to-names'.
325This is used when the user does not set `mail-dont-reply-to-names'
326explicitly.")
327;;;###autoload
328(make-obsolete-variable 'rmail-default-dont-reply-to-names
329                        'mail-dont-reply-to-names "24.1")
330
331;;;###autoload
332(defcustom rmail-ignored-headers
333  (purecopy
334  (concat "^via:\\|^mail-from:\\|^origin:\\|^references:\\|^sender:"
335	  "\\|^status:\\|^received:\\|^x400-originator:\\|^x400-recipients:"
336	  "\\|^x400-received:\\|^x400-mts-identifier:\\|^x400-content-type:"
337	  "\\|^\\(resent-\\|\\)message-id:\\|^summary-line:\\|^resent-date:"
338	  "\\|^nntp-posting-host:\\|^path:\\|^x-char.*:\\|^x-face:\\|^face:"
339	  "\\|^x-mailer:\\|^delivered-to:\\|^lines:"
340	  "\\|^content-transfer-encoding:\\|^x-coding-system:"
341	  "\\|^return-path:\\|^errors-to:\\|^return-receipt-to:"
342	  "\\|^precedence:\\|^mime-version:"
343	  "\\|^list-owner:\\|^list-help:\\|^list-post:\\|^list-subscribe:"
344	  "\\|^list-id:\\|^list-unsubscribe:\\|^list-archive:"
345	  "\\|^content-length:\\|^nntp-posting-date:\\|^user-agent"
346	  "\\|^importance:\\|^envelope-to:\\|^delivery-date\\|^openpgp:"
347	  "\\|^mbox-line:\\|^cancel-lock:"
348	  "\\|^DomainKey-Signature:\\|^dkim-signature:"
349	  "\\|^ARC-.*:"
350	  "\\|^Received-SPF:"
351	  "\\|^Authentication-Results:"
352	  "\\|^resent-face:\\|^resent-x.*:\\|^resent-organization:\\|^resent-openpgp:"
353	  "\\|^x-.*:"))
354  "Regexp to match header fields that Rmail should normally hide.
355\(See also `rmail-nonignored-headers', which overrides this regexp.)
356This variable is used for reformatting the message header,
357which normally happens once for each message,
358when you view the message for the first time in Rmail.
359To make a change in this variable take effect
360for a message that you have already viewed,
361go to that message and type \\[rmail-toggle-header] twice."
362  :type 'regexp
363  :group 'rmail-headers)
364
365(defcustom rmail-nonignored-headers "^x-spam-status:"
366  "Regexp to match X header fields that Rmail should show.
367This regexp overrides `rmail-ignored-headers'; if both this regexp
368and that one match a certain header field, Rmail shows the field.
369If this is nil, ignore all header fields in `rmail-ignored-headers'.
370
371This variable is used for reformatting the message header,
372which normally happens once for each message,
373when you view the message for the first time in Rmail.
374To make a change in this variable take effect
375for a message that you have already viewed,
376go to that message and type \\[rmail-toggle-header] twice."
377  :type '(choice (const nil) (regexp))
378  :group 'rmail-headers)
379
380;;;###autoload
381(defcustom rmail-displayed-headers nil
382  "Regexp to match Header fields that Rmail should display.
383If nil, display all header fields except those matched by
384`rmail-ignored-headers'."
385  :type '(choice regexp (const :tag "All" nil))
386  :group 'rmail-headers)
387
388;;;###autoload
389(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:")
390  "Headers that should be stripped when retrying a failed message."
391  :type '(choice regexp (const nil :tag "None"))
392  :group 'rmail-headers
393  :version "23.2")	   ; added x-detected-operating-system, x-spam
394
395;;;###autoload
396(defcustom rmail-highlighted-headers (purecopy "^From:\\|^Subject:")
397  "Regexp to match Header fields that Rmail should normally highlight.
398A value of nil means don't highlight.  Uses the face `rmail-highlight'."
399  :type '(choice regexp (const :tag "None" nil))
400  :group 'rmail-headers)
401
402(defface rmail-highlight
403  '((t (:inherit highlight)))
404  "Face to use for highlighting the most important header fields.
405The variable `rmail-highlighted-headers' specifies which headers."
406  :group 'rmail-headers
407  :version "22.1")
408
409(defface rmail-header-name
410  '((t (:inherit font-lock-function-name-face)))
411  "Face to use for highlighting the header names.
412The variable `rmail-font-lock-keywords' specifies which headers
413get highlighted."
414  :group 'rmail-headers
415  :version "23.1")
416
417(defcustom rmail-delete-after-output nil
418  "Non-nil means automatically delete a message that is copied to a file."
419  :type 'boolean
420  :group 'rmail-files)
421
422;;;###autoload
423(defcustom rmail-primary-inbox-list nil
424  "List of files that are inboxes for your primary mail file `rmail-file-name'.
425If this is nil, uses the environment variable MAIL.  If that is
426unset, uses a file named by the function `user-login-name' in the
427directory `rmail-spool-directory' (whose value depends on the
428operating system).  For example, \"/var/mail/USER\"."
429  ;; Don't use backquote here, because we don't want to need it at load time.
430  ;; (That must be an old comment - it's dumped these days.)
431  :type (list 'choice '(const :tag "Default" nil)
432	      (list 'repeat ':value (list (or (getenv "MAIL")
433					      (concat rmail-spool-directory
434						      (user-login-name))))
435		    'file))
436  :group 'rmail-retrieve
437  :group 'rmail-files)
438
439(defcustom rmail-mail-new-frame nil
440  "Non-nil means Rmail makes a new frame for composing outgoing mail.
441This is handy if you want to preserve the window configuration of
442the frame where you have the RMAIL buffer displayed."
443  :type 'boolean
444  :group 'rmail-reply)
445
446;;;###autoload
447(defcustom rmail-secondary-file-directory (purecopy "~/")
448  "Directory for additional secondary Rmail files."
449  :type 'directory
450  :group 'rmail-files)
451;;;###autoload
452(defcustom rmail-secondary-file-regexp (purecopy "\\.xmail\\'")
453  "Regexp for which files are secondary Rmail files."
454  :type 'regexp
455  :group 'rmail-files)
456
457(defcustom rmail-confirm-expunge 'y-or-n-p
458  "Whether and how to ask for confirmation before expunging deleted messages.
459The value, if non-nil is a function to call with a question (string)
460as argument, to ask the user that question."
461  :type '(choice (const :tag "No confirmation" nil)
462		 (const :tag "Confirm with y-or-n-p" y-or-n-p)
463		 (const :tag "Confirm with yes-or-no-p" yes-or-no-p))
464  :version "21.1"
465  :group 'rmail-files)
466(put 'rmail-confirm-expunge 'risky-local-variable t)
467
468;;;###autoload
469(defvar rmail-mode-hook nil
470  "List of functions to call when Rmail is invoked.")
471
472(defvar rmail-get-new-mail-hook nil
473  "List of functions to call when Rmail has retrieved new mail.")
474
475;;;###autoload
476(defcustom rmail-show-message-hook nil
477  "List of functions to call when Rmail displays a message."
478  :type 'hook
479  :options '(goto-address)
480  :group 'rmail)
481
482(defvar rmail-quit-hook nil
483  "List of functions to call when quitting out of Rmail.")
484
485(defvar rmail-delete-message-hook nil
486  "List of functions to call when Rmail deletes a message.
487When the hooks are called, the message has been marked deleted but is
488still the current message in the Rmail buffer.")
489
490;; These may be altered by site-init.el to match the format of mmdf files
491;;  delimiting used on a given host (delim1 and delim2 from the config
492;;  files).
493
494(defvar rmail-mmdf-delim1 "^\001\001\001\001\n"
495  "Regexp marking the start of an mmdf message.")
496(defvar rmail-mmdf-delim2 "^\001\001\001\001\n"
497  "Regexp marking the end of an mmdf message.")
498
499(defcustom rmail-automatic-folder-directives nil
500  "List of directives specifying how to automatically file messages.
501Whenever Rmail shows a message in the folder that `rmail-file-name'
502specifies, it calls `rmail-auto-file' to maybe file the message in
503another folder according to this list.  Messages that are already
504marked as `filed', or are in different folders, are left alone.
505
506Each element of the list is of the form:
507
508  (FOLDERNAME FIELD REGEXP [ FIELD REGEXP ] ... )
509
510FOLDERNAME is the name of a folder in which to put the message.
511If FOLDERNAME is nil then Rmail deletes the message, and moves on to
512the next.  If FOLDERNAME is \"/dev/null\", Rmail deletes the message,
513but does not move to the next.
514
515FIELD is the name of a header field in the message, such as
516\"subject\" or \"from\".  A FIELD of \"to\" includes all text
517from both the \"to\" and \"cc\" headers.
518
519REGEXP is a regular expression to match (case-sensitively) against
520the preceding specified FIELD.
521
522There may be any number of FIELD/REGEXP pairs.
523All pairs must match for a directive to apply to a message.
524For a given message, Rmail applies only the first matching directive.
525
526Examples:
527  (\"/dev/null\" \"from\" \"@spam.com\") ; delete all mail from spam.com
528  (\"RMS\" \"from\" \"rms@\") ; save all mail from RMS.
529"
530  :group 'rmail
531  :version "21.1"
532  :type '(repeat (sexp :tag "Directive")))
533
534(defvar rmail-reply-prefix "Re: "
535  "String to prepend to Subject line when replying to a message.")
536
537;; Note: this is matched with case-fold-search bound to t.
538(defcustom rmail-re-abbrevs
539  "\\(RE\\|رد\\|回复\\|回覆\\|SV\\|Antw\\|VS\\|REF\\|AW\\|ΑΠ\\|ΣΧΕΤ\\|השב\\|Vá\\|R\\|RIF\\|BLS\\|RES\\|Odp\\|YNT\\|ATB\\)"
540  "Regexp with localized 'Re:' abbreviations in various languages."
541  :version "28.1"
542  :type 'regexp)
543
544;; Some mailers use "Re(2):" or "Re^2:" or "Re: Re:" or "Re[2]:".
545;; This pattern should catch all the common variants.
546;; rms: I deleted the change to delete tags in square brackets
547;; because they mess up RT tags.
548(defvar rmail-reply-regexp
549  (concat "\\`\\("
550          rmail-re-abbrevs
551          "\\(([0-9]+)\\|\\[[0-9]+\\]\\|\\^[0-9]+\\)?\u00a0*[::] *\\)*")
552  "Regexp to delete from Subject line before inserting `rmail-reply-prefix'.")
553
554(defcustom rmail-display-summary nil
555  "If non-nil, Rmail always displays the summary buffer."
556  :group 'rmail-summary
557  :type 'boolean)
558
559(defvar rmail-inbox-list nil)
560(put 'rmail-inbox-list 'permanent-local t)
561
562(defvar rmail-buffer nil
563  "The RMAIL buffer related to the current buffer.
564In an RMAIL buffer, this holds the RMAIL buffer itself.
565In a summary buffer, this holds the RMAIL buffer it is a summary for.")
566(put 'rmail-buffer 'permanent-local t)
567
568(defvar rmail-was-converted nil
569  "Non-nil in an Rmail buffer that was just converted from Babyl format.")
570(put 'rmail-was-converted 'permanent-local t)
571
572(defvar rmail-seriously-modified nil
573  "Non-nil in an Rmail buffer that has been modified in a major way.")
574(put 'rmail-seriously-modified 'permanent-local t)
575
576;; Message counters and markers.  Deleted flags.
577
578(defvar rmail-current-message nil
579  "Integer specifying the message currently being displayed in this folder.
580Counts messages from 1 to `rmail-total-messages'.  A value of 0
581means there are no messages in the folder.")
582(put 'rmail-current-message 'permanent-local t)
583
584(defvar rmail-total-messages nil
585  "Integer specifying the total number of messages in this folder.
586Includes deleted messages.")
587(put 'rmail-total-messages 'permanent-local t)
588
589(defvar rmail-message-vector nil
590  "Vector of markers specifying the start and end of each message.
591Element N and N+1 specify the start and end of message N.")
592(put 'rmail-message-vector 'permanent-local t)
593
594(defvar rmail-deleted-vector nil
595  "A string of length `rmail-total-messages' plus one.
596Character N is either a space or \"D\", according to whether
597message N is deleted or not.")
598(put 'rmail-deleted-vector 'permanent-local t)
599
600(defvar rmail-msgref-vector nil
601  "In an Rmail buffer, a vector whose Nth element is a list (N).
602When expunging renumbers messages, these lists are modified
603by substituting the new message number into the existing list.")
604(put 'rmail-msgref-vector 'permanent-local t)
605
606(defvar rmail-overlay-list nil)
607(put 'rmail-overlay-list 'permanent-local t)
608
609;; These are used by autoloaded rmail-summary.
610
611(defvar rmail-summary-buffer nil)
612(put 'rmail-summary-buffer 'permanent-local t)
613(defvar rmail-summary-vector nil
614  "In an Rmail buffer, vector of (newline-terminated) strings.
615Element N specifies the summary line for message N+1.")
616(put 'rmail-summary-vector 'permanent-local t)
617
618;; Rmail buffer swapping variables.
619
620(defvar-local rmail-buffer-swapped nil
621  "If non-nil, `rmail-buffer' is swapped with `rmail-view-buffer'.")
622(put 'rmail-buffer-swapped 'permanent-local t)
623
624(defvar-local rmail-view-buffer nil
625  "Buffer which holds RMAIL message for MIME displaying.")
626(put 'rmail-view-buffer 'permanent-local t)
627
628;; `Sticky' default variables.
629
630;; Last individual label specified to a or k.
631(defvar rmail-last-label nil)
632
633;; Last set of values specified to C-M-n, C-M-p, C-M-s or C-M-l.
634(defvar rmail-last-multi-labels nil)
635
636(defvar rmail-last-regexp nil)
637(put 'rmail-last-regexp 'permanent-local t)
638
639;; Note that rmail-output-read-file-name modifies this.
640(defcustom rmail-default-file "~/xmail"
641  "Default file name for \\[rmail-output]."
642  :type 'file
643  :group 'rmail-files)
644(defcustom rmail-default-body-file "~/mailout"
645  "Default file name for \\[rmail-output-body-to-file]."
646  :type 'file
647  :group 'rmail-files
648  :version "20.3")
649
650;; Mule and MIME related variables.
651
652;;;###autoload
653(defvar rmail-file-coding-system nil
654  "Coding system used in RMAIL file.
655
656This is set to nil by default.")
657
658(defcustom rmail-get-coding-function nil
659  "Function of no args to try to determine coding system for a message.
660If nil, just search for `rmail-mime-charset-pattern'."
661  :type '(choice (const nil) function)
662  :group 'rmail
663  :version "24.4")
664
665(defcustom rmail-enable-mime t
666  "If non-nil, RMAIL automatically displays decoded MIME messages.
667For this to work, the feature specified by `rmail-mime-feature' must
668be available."
669  :type 'boolean
670  :version "23.3"
671  :group 'rmail)
672
673(defcustom rmail-enable-mime-composing t
674  "If non-nil, use `rmail-insert-mime-forwarded-message-function' to forward."
675  :type 'boolean
676  :version "24.1"			; nil -> t
677  :group 'rmail)
678
679(defvar rmail-show-mime-function nil
680  "Function of no argument called to show a decoded MIME message.
681This function is called when `rmail-enable-mime' is non-nil.
682The package providing MIME support should set this.")
683
684;;;###autoload
685(defvar rmail-insert-mime-forwarded-message-function nil
686  "Function to insert a message in MIME format so it can be forwarded.
687This function is called if `rmail-enable-mime' and
688`rmail-enable-mime-composing' are non-nil.
689It is called with one argument FORWARD-BUFFER, which is a
690buffer containing the message to forward.  The current buffer
691is the outgoing mail buffer.")
692
693(defvar rmail-insert-mime-resent-message-function nil
694  "Function to insert a message in MIME format so it can be resent.
695This function is called by `rmail-resend' if `rmail-enable-mime' is non-nil.
696It is called with one argument FORWARD-BUFFER, which is a
697buffer containing the message to forward.  The current buffer
698is the outgoing mail buffer.")
699
700;; FIXME one might want to pass a LIMIT, as per
701;; rmail-search-mime-header-function.
702(defvar rmail-search-mime-message-function nil
703  "Function to check if a regexp matches a MIME message.
704This function is called by `rmail-search-message' if
705`rmail-enable-mime' is non-nil.  It is called (with point at the
706start of the message) with two arguments MSG and REGEXP, where
707MSG is the message number, REGEXP is the regular expression.")
708
709(defvar rmail-search-mime-header-function nil
710  "Function to check if a regexp matches a header of MIME message.
711This function is called by `rmail-message-regexp-p-1' if
712`rmail-enable-mime' is non-nil.  It is called (with point at the
713start of the header) with three arguments MSG, REGEXP, and LIMIT,
714where MSG is the message number, REGEXP is the regular
715expression, LIMIT is the position specifying the end of header.")
716
717(defvar rmail-mime-feature 'rmailmm
718  "Feature to require for MIME support in Rmail.
719When starting Rmail, if `rmail-enable-mime' is non-nil, this
720feature is loaded with `require'.  The default value is `rmailmm'.
721
722The library should set the variable `rmail-show-mime-function'
723to an appropriate value, and optionally also set
724`rmail-search-mime-message-function',
725`rmail-search-mime-header-function',
726`rmail-insert-mime-forwarded-message-function', and
727`rmail-insert-mime-resent-message-function'.")
728
729(defvar rmail-mime-charset-pattern
730  (concat "^content-type:[ \t]*text/plain;"
731	  "\\(?:[ \t\n]*\\(?:format\\|delsp\\)=\"?[-a-z0-9]+\"?;\\)*"
732	  "[ \t\n]*charset=\"?\\([^ \t\n\";]+\\)\"?")
733  "Regexp to match MIME-charset specification in a header of message.
734The first parenthesized expression should match the MIME-charset name.")
735
736
737(defvar rmail-unix-mail-delimiter
738  (let ((time-zone-regexp
739	 (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
740		 "\\|[-+]?[0-9][0-9][0-9][0-9]"
741		 "\\|"
742		 "\\) *")))
743    (concat
744     "From "
745
746     ;; Many things can happen to an RFC 822 (or later) mailbox before it is
747     ;; put into a `From' line.  The leading phrase can be stripped, e.g.
748     ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
749     ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
750     ;; can be removed, e.g.
751     ;;		From: joe@y.z (Joe	K
752     ;;			User)
753     ;; can yield `From joe@y.z (Joe 	K Fri Mar 22 08:11:15 1996', and
754     ;;		From: Joe User
755     ;;			<joe@y.z>
756     ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
757     ;; The mailbox can be removed or be replaced by white space, e.g.
758     ;;		From: "Joe User"{space}{tab}
759     ;;			<joe@y.z>
760     ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
761     ;; where {space} and {tab} represent the Ascii space and tab characters.
762     ;; We want to match the results of any of these manglings.
763     ;; The following regexp rejects names whose first characters are
764     ;; obviously bogus, but after that anything goes.
765     "\\([^\0-\b\n-\r\^?].*\\)? "
766
767     ;; The time the message was sent.
768     "\\([^\0-\r \^?]+\\) +"				; day of the week
769     "\\([^\0-\r \^?]+\\) +"				; month
770     "\\([0-3]?[0-9]\\) +"				; day of month
771     "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"	; time of day
772
773     ;; Perhaps a time zone, specified by an abbreviation, or by a
774     ;; numeric offset.
775     time-zone-regexp
776
777     ;; The year.
778     " \\([0-9][0-9]+\\) *"
779
780     ;; On some systems the time zone can appear after the year, too.
781     time-zone-regexp
782
783     ;; Old uucp cruft.
784     "\\(remote from .*\\)?"
785
786     "\n"))
787  "Regexp matching the delimiter of messages in UNIX mail format
788\(UNIX From lines), minus the initial ^.  Note that if you change
789this expression, you must change the code in `rmail-nuke-pinhead-header'
790that knows the exact ordering of the \\( \\) subexpressions.")
791
792;; FIXME the rmail-header-name headers ought to be customizable.
793;; It seems a bit arbitrary, for example, that all of the Date: line
794;; gets highlighted.
795(defvar rmail-font-lock-keywords
796  ;; These are all matched case-insensitively.
797  (eval-when-compile
798    (let* ((cite-chars "[>|}]")
799	   (cite-prefix "[:alpha:]")
800	   (cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
801      (list '("^\\(From\\|Sender\\|Resent-From\\):"
802	      . 'rmail-header-name)
803	    '("^\\(Mail-\\)?Reply-To:.*$" . 'rmail-header-name)
804	    ;; FIXME Mail-Followup-To should probably be here too.
805	    '("^Subject:" . 'rmail-header-name)
806	    '("^X-Spam-Status:" . 'rmail-header-name)
807	    '("^\\(To\\|Apparently-To\\|Cc\\|Newsgroups\\):"
808	      . 'rmail-header-name)
809	    ;; Use MATCH-ANCHORED to effectively anchor the regexp left side.
810	    `(,cite-chars
811	      (,(concat "\\=[ \t]*"
812			"\\(\\(\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
813			"\\(" cite-chars "[ \t]*\\)\\)+\\)"
814			"\\(.*\\)")
815	       (beginning-of-line) (end-of-line)
816	       (1 font-lock-comment-delimiter-face nil t)
817	       (5 font-lock-comment-face nil t)))
818	    '("^\\(X-[a-z0-9-]+\\|In-Reply-To\\|Date\\):.*\\(\n[ \t]+.*\\)*$"
819	      . 'rmail-header-name))))
820  "Additional expressions to highlight in Rmail mode.")
821
822;; Rmail does not expect horizontal splitting.  (Bug#2282)
823(defun rmail-pop-to-buffer (&rest args)
824  "Like `pop-to-buffer', but with `split-width-threshold' set to nil."
825  (let (split-width-threshold)
826    (apply 'pop-to-buffer args)))
827
828;; Perform BODY in the summary buffer
829;; in such a way that its cursor is properly updated in its own window.
830(defmacro rmail-select-summary (&rest body)
831  `(let ((total rmail-total-messages))
832     (if (rmail-summary-displayed)
833	 (let ((window (selected-window)))
834	   (save-excursion
835	     (unwind-protect
836		 (progn
837		   (rmail-pop-to-buffer rmail-summary-buffer)
838		   ;; rmail-total-messages is a buffer-local var
839		   ;; in the rmail buffer.
840		   ;; This way we make it available for the body
841		   ;; even tho the rmail buffer is not current.
842		   (let ((rmail-total-messages total))
843		     ,@body))
844	       (select-window window))))
845       (with-current-buffer rmail-summary-buffer
846	 (let ((rmail-total-messages total))
847	   ,@body)))
848     (rmail-maybe-display-summary)))
849
850;;;; *** Rmail Mode ***
851
852(defun rmail-require-mime-maybe ()
853  "Require `rmail-mime-feature' if that is non-nil.
854Signal an error and set `rmail-mime-feature' to nil if the feature
855isn't provided."
856  (when rmail-enable-mime
857    (condition-case nil
858	(require rmail-mime-feature)
859      (error
860       (display-warning
861	'rmail
862	(format-message "Although MIME support is requested
863through `rmail-enable-mime' being non-nil, the required feature
864`%s' (the value of `rmail-mime-feature')
865is not available in the current session.
866So, MIME support is turned off for the moment."
867		rmail-mime-feature)
868	:warning)
869       (setq rmail-enable-mime nil)))))
870
871
872;;;###autoload
873(defun rmail (&optional file-name-arg)
874  "Read and edit incoming mail.
875Moves messages into file named by `rmail-file-name' and edits that
876file in RMAIL Mode.
877Type \\[describe-mode] once editing that file, for a list of RMAIL commands.
878
879May be called with file name as argument; then performs rmail editing on
880that file, but does not copy any new mail into the file.
881Interactively, if you supply a prefix argument, then you
882have a chance to specify a file name with the minibuffer.
883
884If `rmail-display-summary' is non-nil, make a summary for this RMAIL file."
885  (interactive (if current-prefix-arg
886		   (list (read-file-name "Run rmail on RMAIL file: "))))
887  (rmail-require-mime-maybe)
888  (let* ((file-name (expand-file-name (or file-name-arg rmail-file-name)))
889	 ;; Use find-buffer-visiting, not get-file-buffer, for those users
890	 ;; who have find-file-visit-truename set to t.
891	 (existed (find-buffer-visiting file-name))
892	 run-mail-hook mail-buf msg-shown)
893    ;; Determine if an existing mail file has been changed behind the
894    ;; scene...
895    (if (and existed (not (verify-visited-file-modtime existed)))
896	;; The mail file has been changed.  Revisit it and reset the
897	;; message state variables when in rmail mode.
898	(progn
899	  (find-file file-name)
900	  (when (and (verify-visited-file-modtime existed)
901		     (eq major-mode 'rmail-mode))
902	    (rmail-swap-buffers-maybe)
903	    (rmail-set-message-counters)))
904      ;; The mail file is either unchanged or not visited.  Visit it.
905      (switch-to-buffer
906       (let ((enable-local-variables nil)
907	     ;; Force no-conversion by default, since that's what
908	     ;; pre-mbox Rmail did with BABYL files (via
909	     ;; auto-coding-regexp-alist).
910	     (coding-system-for-read
911	      (or coding-system-for-read 'no-conversion)))
912	 (find-file-noselect file-name))))
913    ;; Ensure that the collection and view buffers are in sync and
914    ;; ensure that a message is not being edited.
915    (if (eq major-mode 'rmail-mode)
916	(rmail-swap-buffers-maybe))
917    (if (eq major-mode 'rmail-edit-mode)
918	(error "Exit Rmail Edit mode before getting new mail"))
919    (or (and existed (> (buffer-size) 0))
920	(setq run-mail-hook t))
921    ;; Ensure that the Rmail file is in mbox format, the buffer is in
922    ;; Rmail mode and has been scanned to find all the messages
923    ;; (setting the global message variables in the process).
924    (rmail-convert-file-maybe)
925    (unless (eq major-mode 'rmail-mode)
926      (rmail-mode-2))
927    (goto-char (point-max))
928    (rmail-maybe-set-message-counters)
929    (setq mail-buf rmail-buffer)
930    ;; Show the first unread message and process summary mode.
931    (unwind-protect
932	;; Only get new mail when there is not a file name argument.
933	(unless file-name-arg
934	  (setq msg-shown (rmail-get-new-mail)))
935      (progn
936	(set-buffer mail-buf)
937	(or msg-shown
938	    (rmail-show-message (rmail-first-unseen-message)))
939	(if rmail-display-summary (rmail-summary))
940	(rmail-construct-io-menu)
941	(if run-mail-hook
942	    (run-hooks 'rmail-mode-hook))))))
943
944(defun rmail-convert-file-maybe ()
945  "Determine if the file needs to be converted to mbox format."
946  (widen)
947  (goto-char (point-min))
948  ;; Detect previous Babyl format files.
949  (let ((case-fold-search nil))
950    (cond ((looking-at "BABYL OPTIONS:")
951	   ;; The file is Babyl version 5.  Use unrmail to convert
952	   ;; it.
953	   (rmail-convert-babyl-to-mbox))
954	  ((looking-at "Version: 5\n")
955	   ;; Losing babyl file made by old version of Rmail.  Fix the
956	   ;; babyl file header and use unrmail to convert to mbox
957	   ;; format.
958	   (let ((buffer-read-only nil))
959	     (insert "BABYL OPTIONS: -*- rmail -*-\n")
960	     (rmail-convert-babyl-to-mbox)))
961	  ((equal (point-min) (point-max))
962	   (message "Empty Rmail file."))
963	  ((looking-at "From "))
964	  (t (error "Invalid mbox file")))))
965
966(defun rmail-error-bad-format (&optional msgnum)
967  "Report that the buffer is not in the mbox file format.
968MSGNUM, if present, indicates the malformed message."
969  (if msgnum
970      (error "Message %d is not a valid RFC 822 (or later) message" msgnum)
971    (error "Message is not a valid RFC 822 (or later) message")))
972
973(defun rmail-convert-babyl-to-mbox ()
974  "Convert the mail file from Babyl version 5 to mbox.
975This function also reinitializes local variables used by Rmail."
976  (let ((old-file (make-temp-file "rmail"))
977	(new-file (make-temp-file "rmail")))
978    (unwind-protect
979	(progn
980	  (kill-all-local-variables)
981	  (write-region (point-min) (point-max) old-file)
982	  (unrmail old-file new-file)
983	  (message "Replacing BABYL format with mbox format...")
984	  (let ((inhibit-read-only t)
985		(coding-system-for-read 'raw-text)
986		(buffer-undo-list t))
987	    (erase-buffer)
988	    (insert-file-contents new-file)
989	    ;; Rmail buffers need to be saved with Unix EOLs, or else
990	    ;; the format will not be recognized.
991	    (set-buffer-file-coding-system 'raw-text-unix)
992	    (rmail-mode-1)
993	    (rmail-perm-variables)
994	    (rmail-variables)
995	    (setq rmail-was-converted t)
996	    (rmail-dont-modify-format)
997	    (goto-char (point-max))
998	    (rmail-set-message-counters))
999	  (message "Replacing BABYL format with mbox format...done"))
1000      (delete-file old-file)
1001      (delete-file new-file))))
1002
1003(defun rmail-get-coding-system ()
1004  "Return a suitable coding system to use for the current mail message.
1005The buffer is expected to be narrowed to just the header of the message."
1006  (save-excursion
1007    (goto-char (point-min))
1008    (or (if rmail-get-coding-function
1009	    (funcall rmail-get-coding-function))
1010	(if (re-search-forward rmail-mime-charset-pattern nil t)
1011	    (coding-system-from-name (match-string 1))
1012	  'undecided))))
1013
1014;;; Set up Rmail mode keymaps
1015
1016(defvar rmail-mode-map
1017  (let ((map (make-keymap)))
1018    (suppress-keymap map)
1019    (define-key map "a"      'rmail-add-label)
1020    (define-key map "b"      'rmail-bury)
1021    (define-key map "c"      'rmail-continue)
1022    (define-key map "d"      'rmail-delete-forward)
1023    (define-key map "\C-d"   'rmail-delete-backward)
1024    (define-key map "e"      'rmail-edit-current-message)
1025    ;; If you change this, change the rmail-resend menu-item's :keys.
1026    (define-key map "f"      'rmail-forward)
1027    (define-key map "g"      'rmail-get-new-mail)
1028    (define-key map "h"      'rmail-summary)
1029    (define-key map "i"      'rmail-input)
1030    (define-key map "j"      'rmail-show-message)
1031    (define-key map "k"      'rmail-kill-label)
1032    (define-key map "l"      'rmail-summary-by-labels)
1033    (define-key map "\e\C-h" 'rmail-summary)
1034    (define-key map "\e\C-l" 'rmail-summary-by-labels)
1035    (define-key map "\e\C-r" 'rmail-summary-by-recipients)
1036    (define-key map "\e\C-s" 'rmail-summary-by-regexp)
1037    (define-key map "\e\C-f" 'rmail-summary-by-senders)
1038    (define-key map "\e\C-t" 'rmail-summary-by-topic)
1039    (define-key map "m"      'rmail-mail)
1040    (define-key map "\em"    'rmail-retry-failure)
1041    (define-key map "n"      'rmail-next-undeleted-message)
1042    (define-key map "\en"    'rmail-next-message)
1043    (define-key map "\e\C-n" 'rmail-next-labeled-message)
1044    (define-key map "o"      'rmail-output)
1045    (define-key map "\C-o"   'rmail-output-as-seen)
1046    (define-key map "p"      'rmail-previous-undeleted-message)
1047    (define-key map "\ep"    'rmail-previous-message)
1048    (define-key map "\e\C-p" 'rmail-previous-labeled-message)
1049    (define-key map "q"      'rmail-quit)
1050    (define-key map "r"      'rmail-reply)
1051    ;; I find I can't live without the default M-r command -- rms.
1052    ;;  (define-key rmail-mode-map "\er"  'rmail-search-backwards)
1053    (define-key map "s"      'rmail-expunge-and-save)
1054    (define-key map "\es"    'rmail-search)
1055    (define-key map "t"      'rmail-toggle-header)
1056    (define-key map "u"      'rmail-undelete-previous-message)
1057    (define-key map "v"      'rmail-mime)
1058    (define-key map "w"      'rmail-output-body-to-file)
1059    (define-key map "\C-c\C-w"    'rmail-widen)
1060    (define-key map "x"      'rmail-expunge)
1061    (define-key map "."      'rmail-beginning-of-message)
1062    (define-key map "/"      'rmail-end-of-message)
1063    (define-key map "<"      'rmail-first-message)
1064    (define-key map ">"      'rmail-last-message)
1065    (define-key map " "      'scroll-up-command)
1066    (define-key map [?\S-\ ] 'scroll-down-command)
1067    (define-key map "\177"   'scroll-down-command)
1068    (define-key map "?"      'describe-mode)
1069    (define-key map "\C-c\C-d" 'rmail-epa-decrypt)
1070    (define-key map "\C-c\C-s\C-d" 'rmail-sort-by-date)
1071    (define-key map "\C-c\C-s\C-s" 'rmail-sort-by-subject)
1072    (define-key map "\C-c\C-s\C-a" 'rmail-sort-by-author)
1073    (define-key map "\C-c\C-s\C-r" 'rmail-sort-by-recipient)
1074    (define-key map "\C-c\C-s\C-c" 'rmail-sort-by-correspondent)
1075    (define-key map "\C-c\C-s\C-l" 'rmail-sort-by-lines)
1076    (define-key map "\C-c\C-s\C-k" 'rmail-sort-by-labels)
1077    (define-key map "\C-c\C-n" 'rmail-next-same-subject)
1078    (define-key map "\C-c\C-p" 'rmail-previous-same-subject)
1079
1080
1081    (define-key map [menu-bar] (make-sparse-keymap))
1082
1083    (define-key map [menu-bar classify]
1084      (cons "Classify" (make-sparse-keymap "Classify")))
1085
1086    (define-key map [menu-bar classify input-menu]
1087      nil)
1088
1089    (define-key map [menu-bar classify output-menu]
1090      nil)
1091
1092    (define-key map [menu-bar classify output-body]
1093      '("Output body to file..." . rmail-output-body-to-file))
1094
1095    (define-key map [menu-bar classify output-inbox]
1096      '("Output..." . rmail-output))
1097
1098    (define-key map [menu-bar classify output]
1099      '("Output as seen..." . rmail-output-as-seen))
1100
1101    (define-key map [menu-bar classify kill-label]
1102      '("Kill Label..." . rmail-kill-label))
1103
1104    (define-key map [menu-bar classify add-label]
1105      '("Add Label..." . rmail-add-label))
1106
1107    (define-key map [menu-bar summary]
1108      (cons "Summary" (make-sparse-keymap "Summary")))
1109
1110    (define-key map [menu-bar summary senders]
1111      '("By Senders..." . rmail-summary-by-senders))
1112
1113    (define-key map [menu-bar summary labels]
1114      '("By Labels..." . rmail-summary-by-labels))
1115
1116    (define-key map [menu-bar summary recipients]
1117      '("By Recipients..." . rmail-summary-by-recipients))
1118
1119    (define-key map [menu-bar summary topic]
1120      '("By Topic..." . rmail-summary-by-topic))
1121
1122    (define-key map [menu-bar summary regexp]
1123      '("By Regexp..." . rmail-summary-by-regexp))
1124
1125    (define-key map [menu-bar summary all]
1126      '("All" . rmail-summary))
1127
1128    (define-key map [menu-bar mail]
1129      (cons "Mail" (make-sparse-keymap "Mail")))
1130
1131    (define-key map [menu-bar mail rmail-get-new-mail]
1132      '("Get New Mail" . rmail-get-new-mail))
1133
1134    (define-key map [menu-bar mail lambda]
1135      '("----"))
1136
1137    (define-key map [menu-bar mail continue]
1138      '("Continue" . rmail-continue))
1139
1140    (define-key map [menu-bar mail resend]
1141    '(menu-item "Resend..." rmail-resend :keys "C-u f"))
1142
1143    (define-key map [menu-bar mail forward]
1144      '("Forward" . rmail-forward))
1145
1146    (define-key map [menu-bar mail retry]
1147      '("Retry" . rmail-retry-failure))
1148
1149    (define-key map [menu-bar mail reply]
1150      '("Reply" . rmail-reply))
1151
1152    (define-key map [menu-bar mail mail]
1153      '("Mail" . rmail-mail))
1154
1155    (define-key map [menu-bar delete]
1156      (cons "Delete" (make-sparse-keymap "Delete")))
1157
1158    (define-key map [menu-bar delete expunge/save]
1159      '("Expunge/Save" . rmail-expunge-and-save))
1160
1161    (define-key map [menu-bar delete expunge]
1162      '("Expunge" . rmail-expunge))
1163
1164    (define-key map [menu-bar delete undelete]
1165      '("Undelete" . rmail-undelete-previous-message))
1166
1167    (define-key map [menu-bar delete delete]
1168      '("Delete" . rmail-delete-forward))
1169
1170    (define-key map [menu-bar move]
1171      (cons "Move" (make-sparse-keymap "Move")))
1172
1173    (define-key map [menu-bar move search-back]
1174      '("Search Back..." . rmail-search-backwards))
1175
1176    (define-key map [menu-bar move search]
1177      '("Search..." . rmail-search))
1178
1179    (define-key map [menu-bar move previous]
1180      '("Previous Nondeleted" . rmail-previous-undeleted-message))
1181
1182    (define-key map [menu-bar move next]
1183      '("Next Nondeleted" . rmail-next-undeleted-message))
1184
1185    (define-key map [menu-bar move last]
1186      '("Last" . rmail-last-message))
1187
1188    (define-key map [menu-bar move first]
1189      '("First" . rmail-first-message))
1190
1191    (define-key map [menu-bar move previous]
1192      '("Previous" . rmail-previous-message))
1193
1194    (define-key map [menu-bar move next]
1195      '("Next" . rmail-next-message))
1196
1197   map)
1198  "Keymap used in Rmail mode.")
1199
1200;; Rmail toolbar
1201(defvar rmail-tool-bar-map
1202  (let ((map (make-sparse-keymap)))
1203    (tool-bar-local-item-from-menu 'rmail-get-new-mail "mail/inbox"
1204				   map rmail-mode-map)
1205    (tool-bar-local-item-from-menu 'rmail-next-undeleted-message "right-arrow"
1206				   map rmail-mode-map)
1207    (tool-bar-local-item-from-menu 'rmail-previous-undeleted-message "left-arrow"
1208				   map rmail-mode-map)
1209    (tool-bar-local-item-from-menu 'rmail-search "search"
1210				   map rmail-mode-map)
1211    (tool-bar-local-item-from-menu 'rmail-input "open"
1212				   map rmail-mode-map)
1213    (tool-bar-local-item-from-menu 'rmail-mail "mail/compose"
1214				   map rmail-mode-map)
1215    (tool-bar-local-item-from-menu 'rmail-reply "mail/reply-all"
1216				   map rmail-mode-map)
1217    (tool-bar-local-item-from-menu 'rmail-forward "mail/forward"
1218				   map rmail-mode-map)
1219    (tool-bar-local-item-from-menu 'rmail-delete-forward "close"
1220				   map rmail-mode-map)
1221    (tool-bar-local-item-from-menu 'rmail-output "mail/move"
1222				   map rmail-mode-map)
1223    (tool-bar-local-item-from-menu 'rmail-output-body-to-file "mail/save"
1224				   map rmail-mode-map)
1225    (tool-bar-local-item-from-menu 'rmail-expunge "delete"
1226				   map rmail-mode-map)
1227    map))
1228
1229
1230
1231;; Rmail mode is suitable only for specially formatted data.
1232(put 'rmail-mode 'mode-class 'special)
1233
1234(defun rmail-mode-kill-summary ()
1235  (if rmail-summary-buffer (kill-buffer rmail-summary-buffer)))
1236
1237(defvar rmail-enable-multibyte)         ; dynamically bound
1238
1239;;;###autoload
1240(defun rmail-mode ()
1241  "Rmail Mode is used by \\<rmail-mode-map>\\[rmail] for editing Rmail files.
1242All normal editing commands are turned off.
1243Instead, these commands are available:
1244
1245\\[rmail-beginning-of-message]	Move point to front of this message.
1246\\[rmail-end-of-message]	Move point to bottom of this message.
1247\\[scroll-up]	Scroll to next screen of this message.
1248\\[scroll-down]	Scroll to previous screen of this message.
1249\\[rmail-next-undeleted-message]	Move to Next non-deleted message.
1250\\[rmail-previous-undeleted-message]	Move to Previous non-deleted message.
1251\\[rmail-next-message]	Move to Next message whether deleted or not.
1252\\[rmail-previous-message]	Move to Previous message whether deleted or not.
1253\\[rmail-first-message]	Move to the first message in Rmail file.
1254\\[rmail-last-message]	Move to the last message in Rmail file.
1255\\[rmail-show-message]	Jump to message specified by numeric position in file.
1256\\[rmail-search]	Search for string and show message it is found in.
1257\\[rmail-delete-forward]	Delete this message, move to next nondeleted.
1258\\[rmail-delete-backward]	Delete this message, move to previous nondeleted.
1259\\[rmail-undelete-previous-message]	Undelete message.  Tries current message, then earlier messages
1260	till a deleted message is found.
1261\\[rmail-edit-current-message]	Edit the current message.  \\[rmail-cease-edit] to return to Rmail.
1262\\[rmail-epa-decrypt]	Decrypt the current message.
1263\\[rmail-expunge]	Expunge deleted messages.
1264\\[rmail-expunge-and-save]	Expunge and save the file.
1265\\[rmail-quit]       Quit Rmail: expunge, save, then switch to another buffer.
1266\\[save-buffer] Save without expunging.
1267\\[rmail-get-new-mail]	Move new mail from system spool directory into this file.
1268\\[rmail-mail]	Mail a message (same as \\[mail-other-window]).
1269\\[rmail-continue]	Continue composing outgoing message started before.
1270\\[rmail-reply]	Reply to this message.  Like \\[rmail-mail] but initializes some fields.
1271\\[rmail-retry-failure]	Send this message again.  Used on a mailer failure message.
1272\\[rmail-forward]	Forward this message to another user.
1273\\[rmail-output]	Output (append) this message to another mail file.
1274\\[rmail-output-as-seen]	Output (append) this message to file as it's displayed.
1275\\[rmail-output-body-to-file]	Save message body to a file.  Default filename comes from Subject line.
1276\\[rmail-input]	Input Rmail file.  Run Rmail on that file.
1277\\[rmail-add-label]	Add label to message.  It will be displayed in the mode line.
1278\\[rmail-kill-label]	Kill label.  Remove a label from current message.
1279\\[rmail-next-labeled-message]   Move to Next message with specified label
1280          (label defaults to last one specified).
1281          Standard labels: filed, unseen, answered, forwarded, deleted.
1282          Any other label is present only if you add it with \\[rmail-add-label].
1283\\[rmail-previous-labeled-message]   Move to Previous message with specified label
1284\\[rmail-summary]	Show headers buffer, with a one line summary of each message.
1285\\[rmail-summary-by-labels]	Summarize only messages with particular label(s).
1286\\[rmail-summary-by-recipients]   Summarize only messages with particular recipient(s).
1287\\[rmail-summary-by-regexp]   Summarize only messages with particular regexp(s).
1288\\[rmail-summary-by-topic]   Summarize only messages with subject line regexp(s).
1289\\[rmail-toggle-header]	Toggle display of complete header."
1290  (interactive)
1291  (let ((finding-rmail-file (not (eq major-mode 'rmail-mode))))
1292    (rmail-mode-2)
1293    (when (and finding-rmail-file
1294	       (null coding-system-for-read))
1295      (let ((rmail-enable-multibyte t))
1296	(rmail-require-mime-maybe)
1297	(rmail-convert-file-maybe)
1298	(goto-char (point-max))
1299	(set-buffer-multibyte t)))
1300    (rmail-set-message-counters)
1301    (rmail-show-message rmail-total-messages)
1302    (when finding-rmail-file
1303      (when rmail-display-summary
1304	(rmail-summary))
1305      (rmail-construct-io-menu))
1306    (run-mode-hooks 'rmail-mode-hook)))
1307
1308(defun rmail-mode-2 ()
1309  (kill-all-local-variables)
1310  (rmail-mode-1)
1311  (rmail-perm-variables)
1312  (rmail-variables))
1313
1314(defun rmail-mode-1 ()
1315  (setq major-mode 'rmail-mode)
1316  (setq mode-name "RMAIL")
1317  (setq buffer-read-only t)
1318  ;; No need to auto save RMAIL files in normal circumstances
1319  ;; because they contain no info except attribute changes
1320  ;; and deletion of messages.
1321  ;; The one exception is when messages are copied into another mbox buffer.
1322  ;; rmail-output enables auto save when you do that.
1323  (setq buffer-auto-save-file-name nil)
1324  (use-local-map rmail-mode-map)
1325  (set-syntax-table text-mode-syntax-table)
1326  (setq local-abbrev-table text-mode-abbrev-table)
1327  ;; Functions to support buffer swapping:
1328  (add-hook 'write-region-annotate-functions
1329	    'rmail-write-region-annotate nil t)
1330  (add-hook 'kill-buffer-hook 'rmail-mode-kill-buffer-hook nil t)
1331  (add-hook 'change-major-mode-hook 'rmail-change-major-mode-hook nil t))
1332
1333(defun rmail-generate-viewer-buffer ()
1334  "Return a reusable buffer suitable for viewing messages.
1335Create the buffer if necessary."
1336  ;; We want to reuse any existing view buffer, so as not to create an
1337  ;; endless number of them.  But we must avoid clashes if we visit
1338  ;; two different rmail files with the same basename (Bug#4593).
1339  (if (and (local-variable-p 'rmail-view-buffer)
1340	   (buffer-live-p rmail-view-buffer))
1341      rmail-view-buffer
1342    (let ((newbuf
1343	   (generate-new-buffer
1344	    (format " *message-viewer %s*"
1345		    (file-name-nondirectory
1346		     (or buffer-file-name (buffer-name)))))))
1347      (with-current-buffer newbuf
1348	(add-hook 'kill-buffer-hook 'rmail-view-buffer-kill-buffer-hook nil t))
1349      newbuf)))
1350
1351(defun rmail-swap-buffers ()
1352  "Swap text between current buffer and `rmail-view-buffer'.
1353This function preserves the current buffer's modified flag, and also
1354sets the current buffer's `buffer-file-coding-system' to that of
1355`rmail-view-buffer'."
1356  (let ((modp-this (buffer-modified-p))
1357	(modp-that
1358	 (with-current-buffer rmail-view-buffer (buffer-modified-p)))
1359	(coding-this buffer-file-coding-system)
1360	(coding-that
1361	 (with-current-buffer rmail-view-buffer
1362	   buffer-file-coding-system)))
1363    (buffer-swap-text rmail-view-buffer)
1364    (setq buffer-file-coding-system coding-that)
1365    (with-current-buffer rmail-view-buffer
1366      (setq buffer-file-coding-system coding-this)
1367      (restore-buffer-modified-p modp-that))
1368    (restore-buffer-modified-p modp-this)))
1369
1370(defun rmail-buffers-swapped-p ()
1371  "Return non-nil if the message collection is in `rmail-view-buffer'."
1372  ;; This is analogous to tar-data-swapped-p in tar-mode.el.
1373  rmail-buffer-swapped)
1374
1375(defun rmail-change-major-mode-hook ()
1376  ;; Bring the actual Rmail messages back into the main buffer.
1377  (when (rmail-buffers-swapped-p)
1378    (rmail-swap-buffers)
1379    (setq rmail-buffer-swapped nil)))
1380
1381(defun rmail-swap-buffers-maybe ()
1382  "Determine if the Rmail buffer is showing a message.
1383If so restore the actual mbox message collection."
1384  (with-current-buffer rmail-buffer
1385    (when (rmail-buffers-swapped-p)
1386      (rmail-swap-buffers)
1387      (setq rmail-buffer-swapped nil))))
1388
1389(defun rmail-modify-format ()
1390  "Warn if important modifications would change Rmail file's format."
1391  (with-current-buffer rmail-buffer
1392    (and rmail-was-converted
1393	 ;; If it's already modified, don't warn again.
1394	 (not rmail-seriously-modified)
1395	 (not
1396	  (yes-or-no-p
1397	   (message "After this, %s would be saved in mbox format.  Proceed? "
1398		    (buffer-name))))
1399	 (error "Aborted"))
1400    (setq rmail-seriously-modified t)))
1401
1402(defun rmail-dont-modify-format ()
1403  (when (and rmail-was-converted (not rmail-seriously-modified))
1404    (set-buffer-modified-p nil)
1405    (message "Marking buffer unmodified to avoid rewriting Babyl file as mbox file")))
1406
1407(defun rmail-mode-kill-buffer-hook ()
1408  ;; Turn off the hook on the view buffer, so we can kill it, then kill it.
1409  (if (buffer-live-p rmail-view-buffer)
1410      (with-current-buffer rmail-view-buffer
1411	(setq kill-buffer-hook nil)
1412	(kill-buffer rmail-view-buffer))))
1413
1414(defun rmail-view-buffer-kill-buffer-hook ()
1415  (error "Can't kill Rmail view buffer `%s' by itself"
1416	 (buffer-name (current-buffer))))
1417
1418;; Set up the permanent locals associated with an Rmail file.
1419(defun rmail-perm-variables ()
1420  (make-local-variable 'rmail-last-regexp)
1421  (make-local-variable 'rmail-deleted-vector)
1422  (setq-local rmail-was-converted nil)
1423  (setq-local rmail-seriously-modified nil)
1424  (setq-local rmail-buffer (current-buffer))
1425  (set-buffer-multibyte nil)
1426  (with-current-buffer (setq rmail-view-buffer (rmail-generate-viewer-buffer))
1427    (setq buffer-undo-list t)
1428    ;; Note that this does not erase the buffer.  Should it?
1429    ;; It depends on how this is called.  If somehow called with the
1430    ;; rmail buffers swapped, it would erase the message collection.
1431    (setq-local rmail-overlay-list nil)
1432    (set-buffer-multibyte t)
1433    ;; Force C-x C-s write Unix EOLs.
1434    (set-buffer-file-coding-system 'undecided-unix))
1435  (make-local-variable 'rmail-summary-buffer)
1436  (make-local-variable 'rmail-summary-vector)
1437  (make-local-variable 'rmail-current-message)
1438  (setq-local rmail-total-messages 0)
1439  (make-local-variable 'rmail-message-vector)
1440  (make-local-variable 'rmail-msgref-vector)
1441  (make-local-variable 'rmail-inbox-list)
1442  ;; Provide default set of inboxes for primary mail file ~/RMAIL.
1443  (and (null rmail-inbox-list)
1444       (or (equal buffer-file-name (expand-file-name rmail-file-name))
1445	   (equal buffer-file-truename
1446		  (abbreviate-file-name (file-truename rmail-file-name))))
1447       (setq rmail-inbox-list
1448	     (or rmail-primary-inbox-list
1449		 (list (or (getenv "MAIL")
1450			   ;; FIXME expand-file-name?
1451			   (concat rmail-spool-directory
1452				   (user-login-name)))))))
1453  (setq-local tool-bar-map rmail-tool-bar-map))
1454
1455;; Set up the non-permanent locals associated with Rmail mode.
1456(defun rmail-variables ()
1457  ;; Turn off undo.  We turn it back on in rmail-edit.
1458  (setq buffer-undo-list t)
1459  ;; Don't let a local variables list in a message cause confusion.
1460  (setq-local local-enable-local-variables nil)
1461  ;; Don't turn off auto-saving based on the size of the buffer
1462  ;; because that code does not understand buffer-swapping.
1463  (setq-local auto-save-include-big-deletions t)
1464  (setq-local revert-buffer-function 'rmail-revert)
1465  (setq-local font-lock-defaults
1466              '(rmail-font-lock-keywords
1467                t t nil nil
1468                (font-lock-maximum-size . nil)
1469                (font-lock-dont-widen . t)
1470                (font-lock-inhibit-thing-lock . (lazy-lock-mode fast-lock-mode))))
1471  (setq-local require-final-newline nil)
1472  (setq-local version-control 'never)
1473  (add-hook 'kill-buffer-hook #'rmail-mode-kill-summary nil t)
1474  (setq-local file-precious-flag t)
1475  (setq-local desktop-save-buffer t)
1476  (setq-local save-buffer-coding-system 'no-conversion)
1477  (setq next-error-move-function 'rmail-next-error-move))
1478
1479;; Handle M-x revert-buffer done in an rmail-mode buffer.
1480(defun rmail-revert (arg noconfirm)
1481  (set-buffer rmail-buffer)
1482  (let* ((revert-buffer-function (default-value 'revert-buffer-function))
1483	 (rmail-enable-multibyte enable-multibyte-characters)
1484	 ;; See similar code in `rmail'.
1485	 ;; FIXME needs updating?
1486	 (coding-system-for-read (and rmail-enable-multibyte 'raw-text))
1487	 (before-revert-hook 'rmail-swap-buffers-maybe))
1488    ;; Call our caller again, but this time it does the default thing.
1489    (when (revert-buffer arg noconfirm)
1490      ;; If the user said "yes", and we changed something,
1491      ;; reparse the messages.
1492      (set-buffer rmail-buffer)
1493      (rmail-mode-2)
1494      ;; Convert all or part to Babyl file if possible.
1495      (rmail-convert-file-maybe)
1496      ;; We have read the file as raw-text, so the buffer is set to
1497      ;; unibyte.  Make it multibyte if necessary.
1498      (if (and rmail-enable-multibyte
1499	       (not enable-multibyte-characters))
1500	  (set-buffer-multibyte t))
1501      (goto-char (point-max))
1502      (rmail-set-message-counters)
1503      (rmail-show-message rmail-total-messages)
1504      (run-hooks 'rmail-mode-hook))))
1505
1506(defun rmail-expunge-and-save ()
1507  "Expunge and save RMAIL file."
1508  (interactive)
1509  (set-buffer rmail-buffer)
1510  (rmail-expunge)
1511  ;; No need to swap buffers: rmail-write-region-annotate takes care of it.
1512  ;; (rmail-swap-buffers-maybe)
1513  (save-buffer)
1514  (if (rmail-summary-exists)
1515      (rmail-select-summary (set-buffer-modified-p nil))))
1516
1517(defun rmail-quit ()
1518  "Quit out of RMAIL.
1519Hook `rmail-quit-hook' is run after expunging."
1520  (interactive)
1521  (set-buffer rmail-buffer)
1522  (rmail-expunge t)
1523  (save-buffer)
1524  (when (boundp 'rmail-quit-hook)
1525    (run-hooks 'rmail-quit-hook))
1526  ;; Don't switch to the summary buffer even if it was recently visible.
1527  (when (rmail-summary-exists)
1528    (with-current-buffer rmail-summary-buffer
1529      (set-buffer-modified-p nil))
1530    (replace-buffer-in-windows rmail-summary-buffer)
1531    (bury-buffer rmail-summary-buffer))
1532  (let ((obuf (current-buffer)))
1533    (quit-window)
1534    (replace-buffer-in-windows obuf)))
1535
1536(defun rmail-bury ()
1537  "Bury current Rmail buffer and its summary buffer."
1538  (interactive)
1539  ;; This let var was called rmail-buffer, but that interfered
1540  ;; with the buffer-local var used in summary buffers.
1541  (if (rmail-summary-exists)
1542      (let (window)
1543        (while (setq window (get-buffer-window rmail-summary-buffer))
1544          (quit-window nil window))
1545        (bury-buffer rmail-summary-buffer)))
1546  (quit-window))
1547
1548(defun rmail-duplicate-message ()
1549  "Create a duplicated copy of the current message.
1550The duplicate copy goes into the Rmail file just after the original."
1551  ;; If we are in a summary buffer, switch to the Rmail buffer.
1552  ;; FIXME simpler to swap the contents, not the buffers?
1553  (set-buffer rmail-buffer)
1554  (rmail-modify-format)
1555  (let ((buff (current-buffer))
1556        (n rmail-current-message)
1557        (beg (rmail-msgbeg rmail-current-message))
1558        (end (rmail-msgend rmail-current-message)))
1559    (if (rmail-buffers-swapped-p) (set-buffer rmail-view-buffer))
1560      (widen)
1561      (let ((buffer-read-only nil)
1562          (string (buffer-substring-no-properties beg end)))
1563      (goto-char end)
1564      (insert string))
1565    (set-buffer buff)
1566    (rmail-swap-buffers-maybe)
1567    (goto-char (point-max))
1568    (rmail-set-message-counters)
1569    (set-buffer-modified-p t)
1570    (rmail-show-message-1 n))
1571  (if (rmail-summary-exists)
1572      (rmail-select-summary (rmail-update-summary)))
1573  (message "Message duplicated"))
1574
1575;;;###autoload
1576(defun rmail-input (filename)
1577  "Run Rmail on file FILENAME."
1578  (interactive "FRun rmail on RMAIL file: ")
1579  (rmail filename))
1580
1581;; This used to scan subdirectories recursively, but someone pointed out
1582;; that if the user wants that, person can put all the files in one dir.
1583;; And the recursive scan was slow.  So I took it out.
1584;; rms, Sep 1996.
1585(defun rmail-find-all-files (start)
1586  "Return list of file in dir START that match `rmail-secondary-file-regexp'."
1587  (if (file-accessible-directory-p start)
1588      ;; Don't sort here.
1589      (let* ((case-fold-search t)
1590	     (files (directory-files start t rmail-secondary-file-regexp)))
1591	;; Sort here instead of in directory-files
1592	;; because this list is usually much shorter.
1593	(sort files 'string<))))
1594
1595(defun rmail-list-to-menu (menu-name l action &optional full-name)
1596  (let ((menu (make-sparse-keymap menu-name))
1597	name)
1598    (mapc
1599     (lambda (item)
1600       (let (command)
1601	 (if (consp item)
1602	     (setq command
1603		   (rmail-list-to-menu
1604		    (car item) (cdr item) action
1605		    (if full-name
1606			(concat full-name "/"
1607				(car item))
1608		      (car item)))
1609		   name (car item))
1610	   (setq name item)
1611	   (setq command
1612		 (list 'lambda () '(interactive)
1613		       (list action
1614			     (expand-file-name
1615			      (if full-name
1616				  (concat full-name "/" item)
1617				item)
1618			      rmail-secondary-file-directory)))))
1619	 (define-key menu (vector (intern name))
1620	   (cons name command))))
1621     (reverse l))
1622    menu))
1623
1624;; This command is always "disabled" when it appears in a menu.
1625(put 'rmail-disable-menu 'menu-enable ''nil)
1626
1627(defun rmail-construct-io-menu ()
1628  (let ((files (rmail-find-all-files rmail-secondary-file-directory)))
1629    (if files
1630	(progn
1631	  (define-key rmail-mode-map [menu-bar classify input-menu]
1632	    (cons "Input Rmail File"
1633		  (rmail-list-to-menu "Input Rmail File"
1634				      files
1635				      'rmail-input)))
1636	  (define-key rmail-mode-map [menu-bar classify output-menu]
1637	    (cons "Output Rmail File"
1638		  (rmail-list-to-menu "Output Rmail File"
1639				      files
1640				      'rmail-output))))
1641
1642      (define-key rmail-mode-map [menu-bar classify input-menu]
1643	'("Input Rmail File" . rmail-disable-menu))
1644      (define-key rmail-mode-map [menu-bar classify output-menu]
1645	'("Output Rmail File" . rmail-disable-menu)))))
1646
1647
1648;;;; *** Rmail input ***
1649
1650(declare-function rmail-summary-goto-msg "rmailsum" (&optional n nowarn skip-rmail))
1651(declare-function rmail-summary-mark-undeleted "rmailsum" (n))
1652(declare-function rmail-summary-mark-deleted "rmailsum" (&optional n undel))
1653(declare-function rfc822-addresses "rfc822" (header-text))
1654(declare-function mail-abbrev-make-syntax-table "mailabbrev.el" ())
1655
1656;; RLK feature not added in this version:
1657;; argument specifies inbox file or files in various ways.
1658
1659;; In Babyl, the Mail: header in the preamble overrode rmail-inbox-list.
1660;; Mbox does not have this feature.
1661(defun rmail-get-new-mail (&optional file-name)
1662  "Move any new mail from this Rmail file's inbox files.
1663The buffer-local variable `rmail-inbox-list' specifies the list
1664of inbox files.  By default, this is nil, except for your primary
1665Rmail file `rmail-file-name'.  In this case, when you first visit
1666the Rmail file it is initialized using either
1667`rmail-primary-inbox-list', or the \"MAIL\" environment variable,
1668or the function `user-login-name' and the directory
1669`rmail-spool-directory' (whose value depends on the operating system).
1670
1671The command `set-rmail-inbox-list' sets `rmail-inbox-list' to the
1672value you specify.
1673
1674You can also specify the file to get new mail from just for one
1675instance of this command.  In this case, the file of new mail is
1676not changed or deleted.  Noninteractively, you can pass the inbox
1677file name as an argument.  Interactively, a prefix argument
1678causes us to read a file name and use that file as the inbox.
1679
1680If the variable `rmail-preserve-inbox' is non-nil, new mail will
1681always be left in inbox files rather than deleted.
1682
1683Before doing anything, this runs `rmail-before-get-new-mail-hook'.
1684Just before returning, it runs `rmail-after-get-new-mail-hook',
1685whether or not there is new mail.
1686
1687If there is new mail, it runs `rmail-get-new-mail-hook', saves
1688the updated file, and shows the first unseen message (which might
1689not be a new one).  It returns non-nil if it got any new messages."
1690  (interactive
1691   (list (if current-prefix-arg
1692	     (read-file-name "Get new mail from file: "))))
1693  (run-hooks 'rmail-before-get-new-mail-hook)
1694  ;; If the disk file has been changed from under us,
1695  ;; revert to it before we get new mail.
1696  (or (verify-visited-file-modtime (current-buffer))
1697      (find-file (buffer-file-name)))
1698  (set-buffer rmail-buffer)
1699  (rmail-modify-format)
1700  (rmail-swap-buffers-maybe)
1701  (rmail-maybe-set-message-counters)
1702  (widen)
1703  ;; Get rid of all undo records for this buffer.
1704  (or (eq buffer-undo-list t)
1705      (setq buffer-undo-list nil))
1706  (let ((all-files (if file-name (list file-name) rmail-inbox-list))
1707	(rmail-enable-multibyte t)
1708	found)
1709    (unwind-protect
1710	(progn
1711	  ;; This loops if any members of the inbox list have the same
1712	  ;; basename (see "name conflict" below).
1713	  (while all-files
1714	    (let (;; If buffer has not changed yet, and has not been
1715		  ;; saved yet, don't replace the old backup file now.
1716		  (make-backup-files (and make-backup-files
1717					  (buffer-modified-p)))
1718		  (buffer-read-only nil)
1719		  ;; Don't make undo records while getting mail.
1720		  (buffer-undo-list t)
1721		  files file-last-names) ;; delete-files
1722	      ;; Pull files off all-files onto files as long as there is
1723	      ;; no name conflict.  A conflict happens when two inbox
1724	      ;; file names have the same last component.
1725	      ;; The reason this careful handling is necessary seems
1726	      ;; to be that rmail-insert-inbox-text uses .newmail-BASENAME.
1727	      (while (and all-files
1728			  (not (member (file-name-nondirectory (car all-files))
1729				file-last-names)))
1730		(setq files (cons (car all-files) files)
1731		      file-last-names
1732		      (cons (file-name-nondirectory (car all-files)) files))
1733		(setq all-files (cdr all-files)))
1734	      ;; Put them back in their original order.
1735	      (setq files (nreverse files))
1736	      (goto-char (point-max))
1737	      ;; Make sure we end with a blank line unless there are
1738	      ;; no messages, as required by mbox format (Bug#9974).
1739	      (unless (bobp)
1740		(while (not (looking-back "\n\n" (- (point) 2)))
1741		  (insert "\n")))
1742	      (setq found (or
1743			   (rmail-get-new-mail-1 file-name files nil) ;; delete-files
1744			   found))))
1745	  ;; Move to the first new message unless we have other unseen
1746	  ;; messages before it.
1747	  (if found (rmail-show-message (rmail-first-unseen-message)))
1748	  (run-hooks 'rmail-after-get-new-mail-hook)
1749	  found)
1750      ;; Don't leave the buffer screwed up if we get a disk-full error.
1751      (rmail-show-message))))
1752
1753(defvar rmail-use-spam-filter)
1754(declare-function rmail-get-new-mail-filter-spam "rmail-spam-filter" (nnew))
1755
1756(defun rmail-get-new-mail-1 (file-name files delete-files)
1757  "Return t if new messages are detected without error, nil otherwise."
1758  (save-excursion
1759    (save-restriction
1760      (let ((new-messages 0)
1761	    (spam-filter-p (and (featurep 'rmail-spam-filter)
1762				rmail-use-spam-filter))
1763	    (blurb "")
1764	    result success suffix)
1765	(narrow-to-region (point) (point))
1766	;; Read in the contents of the inbox files, renaming them as
1767	;; necessary, and adding to the list of files to delete
1768	;; eventually.
1769	(unwind-protect
1770	    (progn
1771	      ;; Set modified now to lock the file, so that we don't
1772	      ;; encounter locking problems later in the middle of
1773	      ;; reading the mail.
1774	      (set-buffer-modified-p t)
1775	      (if file-name
1776		  (rmail-insert-inbox-text files nil)
1777		(setq delete-files (rmail-insert-inbox-text files t))))
1778	  ;; If there was no new mail, or we aborted before actually
1779	  ;; trying to get any, mark buffer unmodified.  Otherwise the
1780	  ;; buffer is correctly marked modified and the file locked
1781	  ;; until we save out the new mail.
1782	  (if (= (point-min) (point-max))
1783	      (set-buffer-modified-p nil)))
1784	;; Scan the new text and convert each message to
1785	;; Rmail/mbox format.
1786	(goto-char (point-min))
1787	(skip-chars-forward " \n")
1788	(narrow-to-region (point) (point-max))
1789	(unwind-protect
1790	    (setq new-messages (rmail-add-mbox-headers)
1791		  success t)
1792	  ;; Try to delete the garbage just inserted.
1793	  (or success (delete-region (point-min) (point-max)))
1794	  ;; If we could not convert the file's inboxes, rename the
1795	  ;; files we tried to read so we won't over and over again.
1796	  (if (and (not file-name) (not success))
1797	      (let ((delfiles delete-files)
1798		    (count 0))
1799		(while delfiles
1800		  (while (file-exists-p (format "RMAILOSE.%d" count))
1801		    (setq count (1+ count)))
1802		  (rename-file (car delfiles) (format "RMAILOSE.%d" count))
1803		  (setq delfiles (cdr delfiles))))))
1804	;; Determine if there are messages.
1805	(unless (zerop new-messages)
1806	  ;; There are.  Process them.
1807	  (goto-char (point-min))
1808	  (rmail-count-new-messages)
1809	  (run-hooks 'rmail-get-new-mail-hook)
1810	  (save-buffer))
1811	;; Delete the old files, now that the Rmail file is saved.
1812	(while delete-files
1813	  (condition-case ()
1814	      ;; First, try deleting.
1815	      (condition-case ()
1816		  (delete-file (car delete-files))
1817		(file-error
1818		 ;; If we can't delete it, truncate it.
1819		 (write-region (point) (point) (car delete-files))))
1820	    (file-error nil))
1821	  (setq delete-files (cdr delete-files)))
1822	(if (zerop new-messages)
1823	    (when (or file-name rmail-inbox-list)
1824	      (message "(No new mail has arrived)"))
1825	  (if spam-filter-p
1826	      (setq blurb (rmail-get-new-mail-filter-spam new-messages))))
1827	(if (rmail-summary-exists)
1828	    (rmail-select-summary (rmail-update-summary)))
1829	(setq suffix (if (= 1 new-messages) "" "s"))
1830	(message "%d new message%s read%s" new-messages suffix blurb)
1831	;; Establish the return value.
1832	(setq result (> new-messages 0))
1833	result))))
1834
1835(defun rmail-remote-proto-p (proto)
1836  "Return non-nil if string PROTO refers to a remote mailbox protocol."
1837  (string-match-p "^\\(imap\\|pop\\)s?$" proto))
1838
1839(defun rmail-parse-url (file)
1840  "Parse a mailbox URL string FILE.
1841Return (MAILBOX-NAME PROTO PASSWORD GOT-PASSWORD), where MAILBOX-NAME is
1842the name of the mailbox suitable as argument to the actual version of
1843`movemail', PROTO is the movemail protocol (use `rmail-remote-proto-p'
1844to see if it refers to a remote mailbox), PASSWORD is the password if it
1845should be supplied as a separate argument to `movemail' or nil otherwise,
1846and GOT-PASSWORD is non-nil if the user has supplied the password
1847interactively."
1848  (cond
1849   ((string-match "^\\([^:]+\\)://\\(\\([^:@]+\\)\\(:\\([^@]+\\)\\)?@\\)?.*" file)
1850      (let (got-password supplied-password
1851	    (proto (match-string 1 file))
1852	    (user  (match-string 3 file))
1853	    (pass  (match-string 5 file))
1854	    (host  (substring file (or (match-end 2)
1855				       (+ 3 (match-end 1))))))
1856
1857	(if (rmail-remote-proto-p proto)
1858	    (if (not pass)
1859		(when rmail-remote-password-required
1860		  (setq got-password (not (rmail-have-password)))
1861		  (setq supplied-password (rmail-get-remote-password
1862					   (string-match "^imaps?" proto)
1863                                           user host)))
1864	      ;; FIXME
1865	      ;; The password is embedded.  Strip it out since movemail
1866	      ;; does not really like it, in spite of the movemail spec.
1867	      (setq file (concat proto "://" user "@" host))))
1868
1869	(if (rmail-movemail-variant-p 'emacs)
1870	    (if (string-equal proto "pop")
1871		(list (concat "po:" user ":" host)
1872		      proto
1873		      (or pass supplied-password)
1874		      got-password)
1875	      (error "Emacs movemail does not support %s protocol" proto))
1876	  (list file
1877		proto
1878		(or supplied-password pass)
1879		got-password))))
1880
1881   ((string-match "^po:\\([^:]+\\)\\(:\\(.*\\)\\)?" file)
1882    (let (got-password supplied-password
1883	  (user (match-string 1 file))
1884	  (host (match-string 3 file)))
1885
1886      (when rmail-remote-password-required
1887	(setq got-password (not (rmail-have-password)))
1888	(setq supplied-password (rmail-get-remote-password nil user host)))
1889
1890      (list file "pop" supplied-password got-password)))
1891
1892   (t
1893    (list file nil nil nil))))
1894
1895(defun rmail-unrmail-new-mail (from-file)
1896  "Replace newly read mail in Babyl format with equivalent mbox format.
1897
1898FROM-FILE is the Babyl file from which the new mail should be read."
1899  (let ((to-file (make-temp-file "rmail"))
1900	size)
1901    (unrmail from-file to-file)
1902    (let ((inhibit-read-only t)
1903	  (coding-system-for-read 'raw-text)
1904	  (buffer-undo-list t))
1905      (delete-region (point) (point-max))
1906      (setq size (nth 1 (insert-file-contents to-file)))
1907      (delete-file to-file)
1908      size)))
1909
1910(defun rmail-unrmail-new-mail-maybe (file size)
1911  "If newly read mail from FILE is in Babyl format, convert it to mbox format.
1912
1913SIZE is the original size of the newly read mail.
1914Value is the size of the newly read mail after conversion."
1915  ;; Detect previous Babyl format files.
1916  (let ((case-fold-search nil)
1917	(old-file file))
1918    (cond ((looking-at "BABYL OPTIONS:")
1919	   ;; The new mail is in Babyl version 5 format.  Use unrmail
1920	   ;; to convert it.
1921	   (setq size (rmail-unrmail-new-mail old-file)))
1922	  ((looking-at "Version: 5\n")
1923	   ;; New mail is in Babyl format made by old version of
1924	   ;; Rmail.  Fix the babyl file header and use unrmail to
1925	   ;; convert it.
1926	   (let ((buffer-read-only nil)
1927		 (write-region-annotate-functions nil)
1928		 (write-region-post-annotation-function nil)
1929		 (old-file  (make-temp-file "rmail")))
1930	     (insert "BABYL OPTIONS: -*- rmail -*-\n")
1931	     (forward-line -1)
1932	     (write-region (point) (point-max) old-file)
1933	     (setq size (rmail-unrmail-new-mail old-file))
1934	     (delete-file old-file))))
1935    size))
1936
1937(defun rmail-insert-inbox-text (files renamep)
1938  (let (file tofile delete-files proto got-password password)
1939    (while files
1940      ;; Handle remote mailbox names specially; don't expand as filenames
1941      ;; in case the userid contains a directory separator.
1942      (setq file (car files))
1943      (let ((url-data (rmail-parse-url file)))
1944	(setq file (nth 0 url-data))
1945	(setq proto (nth 1 url-data))
1946	(setq password (nth 2 url-data))
1947	(setq got-password (nth 3 url-data)))
1948
1949      (if proto
1950	  (setq renamep t)
1951	(setq file (file-truename
1952		    (substitute-in-file-name (expand-file-name file)))))
1953      (setq tofile (expand-file-name
1954		    ;; Generate name to move to from inbox name,
1955		    ;; in case of multiple inboxes that need moving.
1956		    (concat ".newmail-"
1957			    (file-name-nondirectory
1958			     (if (memq system-type '(windows-nt cygwin ms-dos))
1959				 ;; cannot have colons in file name
1960				 (string-replace ":" "-" file)
1961			       file)))
1962		    ;; Use the directory of this rmail file
1963		    ;; because it's a nuisance to use the homedir
1964		    ;; if that is on a full disk and this rmail
1965		    ;; file isn't.
1966		    (file-name-directory
1967		     (expand-file-name buffer-file-name))))
1968      ;; Always use movemail to rename the file,
1969      ;; since there can be mailboxes in various directories.
1970      (when (not proto)
1971	;; On some systems, /usr/spool/mail/foo is a directory
1972	;; and the actual inbox is /usr/spool/mail/foo/foo.
1973	(if (file-directory-p file)
1974	    (setq file (expand-file-name (user-login-name)
1975					 file))))
1976      (cond (proto
1977	     (message "Getting mail from %s..."
1978		      (if (rmail-remote-proto-p proto)
1979			  "the remote server"
1980			proto)))
1981	    ((and (file-exists-p tofile)
1982		  (/= 0 (file-attribute-size (file-attributes tofile))))
1983	     (message "Getting mail from %s..." tofile))
1984	    ((and (file-exists-p file)
1985		  (/= 0 (file-attribute-size (file-attributes file))))
1986	     (message "Getting mail from %s..." file)))
1987      ;; Set TOFILE if have not already done so, and
1988      ;; rename or copy the file FILE to TOFILE if and as appropriate.
1989      (cond ((not renamep)
1990	     (setq tofile file))
1991	    ((or (file-exists-p tofile) (and (not proto)
1992					     (not (file-exists-p file))))
1993	     nil)
1994	    (t
1995	     (with-temp-buffer
1996	       (let ((errors (current-buffer)))
1997		 (buffer-disable-undo errors)
1998		 (let ((args
1999			(append
2000			 (list (or rmail-movemail-program "movemail") nil errors nil)
2001			 (if rmail-preserve-inbox
2002			     (list "-p")
2003			   nil)
2004			 (if (rmail-movemail-variant-p 'mailutils)
2005			     (append (list "--emacs") rmail-movemail-flags)
2006			   rmail-movemail-flags)
2007			 (list file tofile)
2008			 (if password (list password) nil))))
2009		   (apply 'call-process args))
2010		 (if (not (buffer-modified-p errors))
2011		     ;; No output => movemail won
2012		     nil
2013		   (set-buffer errors)
2014		   (subst-char-in-region (point-min) (point-max)
2015					 ?\n ?\s)
2016		   (goto-char (point-max))
2017		   (skip-chars-backward " \t")
2018		   (delete-region (point) (point-max))
2019		   (goto-char (point-min))
2020		   (if (looking-at "movemail: ")
2021		       (delete-region (point-min) (match-end 0)))
2022		   (beep t)
2023		   ;; If we just read the password, most likely it is
2024		   ;; wrong.  Otherwise, see if there is a specific
2025		   ;; reason to think that the problem is a wrong passwd.
2026		   (if (and proto
2027                            (rmail-remote-proto-p proto)
2028			    (or got-password
2029				(re-search-forward rmail-remote-password-error
2030						   nil t)))
2031		       (rmail-set-remote-password nil))
2032
2033		   ;; If using Mailutils, remove initial error code
2034		   ;; abbreviation
2035		   (when (rmail-movemail-variant-p 'mailutils)
2036		     (goto-char (point-min))
2037		     (when (looking-at "[A-Z][A-Z0-9_]*:")
2038		       (delete-region (point-min) (match-end 0))))
2039
2040		   (message "movemail: %s"
2041			    (buffer-substring (point-min)
2042					      (point-max)))
2043
2044		   (sit-for 3)
2045		   nil)))))
2046
2047      ;; At this point, TOFILE contains the name to read:
2048      ;; Either the alternate name (if we renamed)
2049      ;; or the actual inbox (if not renaming).
2050      (if (file-exists-p tofile)
2051	  (let ((coding-system-for-read 'no-conversion)
2052		size)
2053	    (goto-char (point-max))
2054	    (setq size
2055		  ;; If new mail is in Babyl format, convert it to mbox.
2056		  (rmail-unrmail-new-mail-maybe
2057		   tofile
2058		   (nth 1 (insert-file-contents tofile))))
2059	    (goto-char (point-max))
2060	    ;; Make sure the read-in mbox data properly ends with a
2061	    ;; blank line unless it is of size 0.
2062	    (unless (zerop size)
2063	      (while (not (looking-back "\n\n" (- (point) 2)))
2064		(insert "\n")))
2065	    (if (not (and rmail-preserve-inbox (string= file tofile)))
2066		(setq delete-files (cons tofile delete-files)))))
2067      (message "")
2068      (setq files (cdr files)))
2069    delete-files))
2070
2071;; Decode the region specified by FROM and TO by CODING.
2072;; If CODING is nil or an invalid coding system, decode by `undecided'.
2073(defun rmail-decode-region (from to coding &optional destination)
2074  (if (or (not coding) (not (coding-system-p coding)))
2075      (setq coding 'undecided))
2076  ;; Use -dos decoding, to remove ^M characters left from base64 or
2077  ;; rogue qp-encoded text.
2078  (decode-coding-region
2079   from to (coding-system-change-eol-conversion coding 1) destination)
2080  ;; Don't reveal the fact we used -dos decoding, as users generally
2081  ;; will not expect the RMAIL buffer to use DOS EOL format.
2082  (cond
2083   ((null destination)
2084    (setq buffer-file-coding-system
2085	  (setq last-coding-system-used
2086		(coding-system-change-eol-conversion coding 0))))
2087   ((bufferp destination)
2088    (with-current-buffer destination
2089      (setq buffer-file-coding-system
2090	    (setq last-coding-system-used
2091		  (coding-system-change-eol-conversion coding 0)))))))
2092
2093(defun rmail-ensure-blank-line ()
2094  "Ensure a message ends in a blank line.
2095Call with point at the end of the message."
2096  (unless (bolp)
2097    (insert "\n"))
2098  (unless (looking-back "\n\n" (- (point) 2))
2099    (insert "\n")))
2100
2101(defun rmail-add-mbox-headers ()
2102  "Validate the RFC 822 (or later) format for the new messages.
2103Point should be at the first new message.
2104An error is signaled if the new messages are not RFC 822 (or later)
2105compliant.
2106Unless an Rmail attribute header already exists, add it to the
2107new messages.  Return the number of new messages."
2108  (save-excursion
2109    (save-restriction
2110      (let ((count 0)
2111	    (start (point))
2112	    (value "------U-")
2113	    (case-fold-search nil)
2114	    (delim (concat "\n\n" rmail-unix-mail-delimiter))
2115	    stop)
2116	;; Detect an empty inbox file.
2117	(unless (= start (point-max))
2118	  ;; Scan the new messages to establish a count and to ensure that
2119	  ;; an attribute header is present.
2120	  (if (looking-at rmail-unix-mail-delimiter)
2121	      (while (not stop)
2122		;; Determine if a new attribute header needs to be
2123		;; added to the message.
2124		(if (search-forward "\n\n" nil t)
2125		    (progn
2126		      (setq count (1+ count))
2127		      (narrow-to-region start (point))
2128		      (unless (mail-fetch-field rmail-attribute-header)
2129			(backward-char 1)
2130			(insert rmail-attribute-header ": " value "\n"))
2131		      (widen))
2132		  (rmail-error-bad-format))
2133		;; Move to the next message.
2134		(if (not (re-search-forward delim nil 'move))
2135		    (setq stop t)
2136		  (goto-char (match-beginning 0))
2137		  (forward-char 2))
2138		(setq start (point)))
2139	    (rmail-error-bad-format)))
2140	count))))
2141
2142(defun rmail-get-header-1 (name)
2143  "Subroutine of `rmail-get-header'.
2144Narrow to header, call `mail-fetch-field' to find header NAME."
2145  (if (search-forward "\n\n" nil t)
2146      (progn
2147        (narrow-to-region (point-min) (point))
2148        (mail-fetch-field name))
2149    (rmail-error-bad-format)))
2150
2151(defun rmail-get-header (name &optional msgnum)
2152  "Return the value of message header NAME, nil if it has none.
2153MSGNUM specifies the message number to get it from.
2154If MSGNUM is nil, use the current message."
2155  (rmail-apply-in-message msgnum 'rmail-get-header-1 name))
2156
2157(defun rmail-set-header-1 (name value)
2158  "Subroutine of `rmail-set-header'.
2159Narrow to headers, set header NAME to VALUE, replacing existing if present.
2160VALUE nil means to remove NAME altogether.
2161
2162Only changes the first instance of NAME.  If VALUE is multi-line,
2163continuation lines should already be indented.  VALUE should not
2164end in a newline."
2165  (if (search-forward "\n\n" nil t)
2166      (progn
2167	(forward-char -1)
2168	(narrow-to-region (point-min) (point))
2169	;; cf mail-fetch-field.
2170	(goto-char (point-min))
2171	(if (let ((case-fold-search t))
2172	      (re-search-forward (concat "^" (regexp-quote name) "[ \t]*:")
2173				 nil 'move))
2174	    (let ((start (point))
2175		  end)
2176	      (while (and (zerop (forward-line 1))
2177			  (looking-at "[ \t]")))
2178	      ;; Back up over newline.
2179	      (forward-char -1)
2180	      (setq end (point))
2181	      (goto-char start)
2182            (if value
2183                (progn
2184		    (delete-region start end)
2185                  (insert " " value))
2186		(delete-region (line-beginning-position) (1+ end))))
2187	  ;; Not already present: insert at end of headers.
2188          (if value (insert name ": " value "\n"))))
2189    (rmail-error-bad-format)))
2190
2191(defun rmail-set-header (name &optional msgnum value)
2192  "Set message header NAME to VALUE in message number MSGNUM.
2193If MSGNUM is nil, use the current message.  NAME and VALUE are strings.
2194VALUE may also be nil, meaning to remove the header."
2195  (rmail-apply-in-message msgnum 'rmail-set-header-1 name value)
2196  (with-current-buffer rmail-buffer
2197    ;; Ensure header changes get saved.
2198    ;; (Note replacing a header with an identical copy modifies.)
2199    (set-buffer-modified-p t)
2200    ;; However: don't save in mbox format over a Babyl file
2201    ;; merely because of this.
2202    (rmail-dont-modify-format)))
2203
2204;;;; *** Rmail Attributes and Keywords ***
2205
2206(defun rmail-get-attr-names (&optional msg)
2207  "Return the message attributes in a comma separated string.
2208MSG specifies the message number to get it from.
2209If MSG is nil, use the current message."
2210  (let ((value (rmail-get-header rmail-attribute-header msg))
2211	(nmax (length rmail-attr-array))
2212	result temp)
2213    (when value
2214      (if (> (length value) nmax)
2215          (message "Warning: corrupt attribute header in message")
2216        (dotimes (index (length value))
2217          (setq temp (and (not (= ?- (aref value index)))
2218                          (nth 1 (aref rmail-attr-array index)))
2219                result
2220                (cond
2221                 ((and temp result) (format "%s, %s" result temp))
2222                 (temp temp)
2223                 (t result)))))
2224      result)))
2225
2226(defun rmail-get-keywords (&optional msg)
2227  "Return the message keywords in a comma separated string.
2228MSG, if non-nil, identifies the message number to use.
2229If nil, that means the current message."
2230  (rmail-get-header rmail-keyword-header msg))
2231
2232(defun rmail-get-labels (&optional msg)
2233  "Return a string with the labels (attributes and keywords) of msg MSG.
2234It is put in comma-separated form.
2235MSG, if non-nil, identifies the message number to use.
2236If nil, that means the current message."
2237  (or msg (setq msg rmail-current-message))
2238  (let (attr-names keywords)
2239    ;; Combine the message attributes and keywords
2240    ;; into a comma-separated list.
2241    (setq attr-names (rmail-get-attr-names msg)
2242	  keywords (rmail-get-keywords msg))
2243    (if (string= keywords "")
2244	(setq keywords nil))
2245    (cond
2246     ;; FIXME ? old rmail did not have spaces in the comma-separated lists.
2247     ((and attr-names keywords) (concat " " attr-names "; " keywords))
2248     (attr-names (concat " " attr-names))
2249     (keywords (concat " " keywords))
2250     (t ""))))
2251
2252(defun rmail-display-labels ()
2253  "Update the current messages's attributes and keywords in mode line."
2254  (let ((blurb (rmail-get-labels)))
2255    (setq mode-line-process
2256	  (format " %d/%d%s"
2257		  rmail-current-message rmail-total-messages blurb))))
2258
2259(defun rmail-get-attr-value (attr state)
2260  "Return the character value for ATTR.
2261ATTR is a (numeric) index, an offset into the mbox attribute
2262header value.  STATE is one of nil, t, or a character value."
2263  (cond
2264   ((numberp state) state)
2265   ((not state) ?-)
2266   (t (nth 0 (aref rmail-attr-array attr)))))
2267
2268(defun rmail-set-attribute-1 (attr state)
2269  "Subroutine of `rmail-set-attribute'.
2270Set Rmail attribute ATTR to STATE in `rmail-attribute-header',
2271creating the header if necessary.  Returns non-nil if a
2272significant attribute change was made."
2273  (let ((limit (search-forward "\n\n" nil t))
2274        (value (rmail-get-attr-value attr state))
2275        (inhibit-read-only t)
2276        altered)
2277    (goto-char (point-min))
2278    (if (search-forward (concat rmail-attribute-header ": ") limit t)
2279        ;; If this message already records attributes, just change the
2280        ;; value for this one.
2281        (let ((missing (- (+ (point) attr) (line-end-position))))
2282          ;; Position point at this attribute, adding attributes if necessary.
2283          (if (> missing 0)
2284              (progn
2285                (end-of-line)
2286                (insert-char ?- missing)
2287                (backward-char 1))
2288            (forward-char attr))
2289          ;; Change this attribute.
2290          (when (/= value (char-after))
2291            (setq altered t)
2292            (delete-char 1)
2293            (insert value)))
2294      ;; Otherwise add a header line to record the attributes and set
2295      ;; all but this one to no.
2296      (let ((header-value "--------"))
2297        (aset header-value attr value)
2298        (goto-char (if limit (1- limit) (point-max)))
2299        (setq altered (/= value ?-))
2300        (insert rmail-attribute-header ": " header-value "\n")))
2301    altered))
2302
2303(defun rmail-set-attribute (attr state &optional msgnum)
2304  "Turn an attribute of a message on or off according to STATE.
2305STATE is either nil or the character (numeric) value associated
2306with the state (nil represents off and non-nil represents on).
2307ATTR is either the index number of the attribute, or a string,
2308both from `rmail-attr-array'.  MSGNUM is message number to
2309change; nil means current message."
2310  (let ((n 0)
2311        (nmax (length rmail-attr-array)))
2312    (while (and (stringp attr)
2313                (< n nmax))
2314      (if (string-equal attr (cadr (aref rmail-attr-array n)))
2315          (setq attr n))
2316      (setq n (1+ n))))
2317  (if (stringp attr)
2318      (error "Unknown attribute `%s'" attr))
2319  ;; Ask for confirmation before setting any attribute except `unseen'
2320  ;; if it would force a format change.
2321  (unless (= attr rmail-unseen-attr-index)
2322    (rmail-modify-format))
2323  (with-current-buffer rmail-buffer
2324    (or msgnum (setq msgnum rmail-current-message))
2325    (when (> msgnum 0)
2326      ;; The "deleted" attribute is also stored in a special vector so
2327      ;; update that too.
2328      (if (= attr rmail-deleted-attr-index)
2329          (rmail-set-message-deleted-p msgnum state))
2330      (if (prog1
2331              (rmail-apply-in-message msgnum 'rmail-set-attribute-1 attr state)
2332            (if (= msgnum rmail-current-message)
2333                (rmail-display-labels)))
2334	  ;; Don't save in mbox format over a Babyl file
2335	  ;; merely because of a change in `unseen' attribute.
2336	  (if (= attr rmail-unseen-attr-index)
2337	      (rmail-dont-modify-format)
2338	    ;; Otherwise, if we modified the file text via the view buffer,
2339	    ;; mark the main buffer modified too.
2340	    (set-buffer-modified-p t))))))
2341
2342(defun rmail-message-attr-p (msg attrs)
2343  "Return non-nil if message number MSG has attributes matching regexp ATTRS."
2344  (let ((value (rmail-get-header rmail-attribute-header msg)))
2345    (and value (string-match attrs value))))
2346
2347(defun rmail-message-unseen-p (msgnum)
2348  "Return non-nil if message number MSGNUM has the unseen attribute."
2349  (rmail-message-attr-p msgnum "......U"))
2350
2351;; FIXME rmail-get-labels does some formatting (eg leading space, `;'
2352;; between attributes and labels), so this might not do what you want.
2353;; Eg see rmail-sort-by-labels.  rmail-get-labels could have an
2354;; optional `noformat' argument.
2355(defun rmail-message-labels-p (msg labels)
2356  "Return non-nil if message number MSG has labels matching regexp LABELS."
2357  (string-match labels (rmail-get-labels msg)))
2358
2359;;;; *** Rmail Message Selection And Support ***
2360
2361(defun rmail-msgend (n)
2362  "Return the end position for message number N."
2363  (marker-position (aref rmail-message-vector (1+ n))))
2364
2365(defun rmail-msgbeg (n)
2366  "Return the start position for message number N."
2367  (marker-position (aref rmail-message-vector n)))
2368
2369(defun rmail-apply-in-message (msgnum function &rest args)
2370  "Call FUNCTION on ARGS while narrowed to message MSGNUM.
2371Point is at the start of the message.
2372This returns what the call to FUNCTION returns.
2373If MSGNUM is nil, use the current message."
2374  (with-current-buffer rmail-buffer
2375    (or msgnum (setq msgnum rmail-current-message))
2376    (when (> msgnum 0)
2377      (let (msgbeg msgend)
2378	(setq msgbeg (rmail-msgbeg msgnum))
2379	(setq msgend (rmail-msgend msgnum))
2380	;; All access to the rmail-buffer's local variables is now finished...
2381	(save-excursion
2382	  ;; ... so it is ok to go to a different buffer.
2383	  (if (rmail-buffers-swapped-p) (set-buffer rmail-view-buffer))
2384	  (save-excursion
2385	    (save-restriction
2386	      (widen)
2387	      (goto-char msgbeg)
2388	      (narrow-to-region msgbeg msgend)
2389	      (apply function args))))))))
2390
2391;; Unused (save for commented out code in rmailedit.el).
2392(defun rmail-widen-to-current-msgbeg (function)
2393  "Call FUNCTION with point at start of internal data of current message.
2394Assumes that bounds were previously narrowed to display the message in Rmail.
2395The bounds are widened enough to move point where desired, then narrowed
2396again afterward.
2397
2398FUNCTION may not change the visible text of the message, but it may
2399change the invisible header text."
2400  (save-excursion
2401    (unwind-protect
2402	(progn
2403	  (narrow-to-region (rmail-msgbeg rmail-current-message)
2404			    (point-max))
2405	  (goto-char (point-min))
2406	  (funcall function))
2407	;; Note: we don't use save-restriction because that does not work right
2408	;; if changes are made outside the saved restriction
2409	;; before that restriction is restored.
2410      (narrow-to-region (rmail-msgbeg rmail-current-message)
2411			(rmail-msgend rmail-current-message)))))
2412
2413;; Manage the message vectors and counters.
2414
2415(defun rmail-forget-messages ()
2416  (unwind-protect
2417      (if (vectorp rmail-message-vector)
2418	  (let* ((v rmail-message-vector)
2419		 (n (length v)))
2420	    (dotimes (i n)
2421	      (if (aref v i)
2422		  (move-marker (aref v i)  nil)))))
2423    (setq rmail-message-vector nil)
2424    (setq rmail-msgref-vector nil)
2425    (setq rmail-deleted-vector nil)))
2426
2427(defun rmail-maybe-set-message-counters ()
2428  (if (not (and rmail-deleted-vector
2429		rmail-message-vector
2430		rmail-current-message
2431		rmail-total-messages))
2432      (rmail-set-message-counters)))
2433
2434(defun rmail-count-new-messages (&optional nomsg)
2435  "Count the number of new messages.
2436The buffer should be narrowed to include only the new messages.
2437Output a helpful message unless NOMSG is non-nil."
2438  (let* ((case-fold-search nil)
2439	 (total-messages 0)
2440	 (messages-head nil)
2441	 (deleted-head nil))
2442    (or nomsg (message "Counting new messages..."))
2443    (goto-char (point-max))
2444    ;; Put at the end of messages-head
2445    ;; the entry for message N+1, which marks
2446    ;; the end of message N.  (N = number of messages).
2447    (setq messages-head (list (point-marker)))
2448    (rmail-set-message-counters-counter (point-min))
2449    (setq rmail-current-message (1+ rmail-total-messages))
2450    (setq rmail-total-messages
2451	  (+ rmail-total-messages total-messages))
2452    (setq rmail-message-vector
2453	  (vconcat rmail-message-vector (cdr messages-head)))
2454    (aset rmail-message-vector
2455	  rmail-current-message (car messages-head))
2456    (setq rmail-deleted-vector
2457	  (concat rmail-deleted-vector deleted-head))
2458    (setq rmail-summary-vector
2459	  (vconcat rmail-summary-vector (make-vector total-messages nil)))
2460    (setq rmail-msgref-vector
2461	  (vconcat rmail-msgref-vector (make-vector total-messages nil)))
2462    ;; Fill in the new elements of rmail-msgref-vector.
2463    (let ((i (1+ (- rmail-total-messages total-messages))))
2464      (while (<= i rmail-total-messages)
2465	(aset rmail-msgref-vector i (list i))
2466	(setq i (1+ i))))
2467    (goto-char (point-min))
2468    (or nomsg (message "Counting new messages...done (%d)" total-messages))))
2469
2470(defun rmail-set-message-counters ()
2471  (rmail-forget-messages)
2472  (save-excursion
2473    (save-restriction
2474      (widen)
2475      (let* ((point-save (point))
2476	     (total-messages 0)
2477	     (messages-after-point)
2478	     (case-fold-search nil)
2479	     (messages-head nil)
2480	     (deleted-head nil))
2481	;; Determine how many messages follow point.
2482	(message "Counting messages...")
2483	(goto-char (point-max))
2484	;; Put at the end of messages-head
2485	;; the entry for message N+1, which marks
2486	;; the end of message N.  (N = number of messages).
2487	(setq messages-head (list (point-marker)))
2488	(setq messages-after-point
2489	      (or (rmail-set-message-counters-counter (min (point) point-save))
2490		  0))
2491
2492	(setq rmail-total-messages total-messages)
2493	(setq rmail-current-message
2494	      (min total-messages
2495		   (max 1 (- total-messages messages-after-point))))
2496
2497	;; Make an element 0 in rmail-message-vector and rmail-deleted-vector
2498	;; which will never be used.
2499	(push nil messages-head)
2500	(push ?0 deleted-head)
2501	(setq rmail-message-vector (apply 'vector messages-head)
2502	      rmail-deleted-vector (concat deleted-head))
2503
2504	(setq rmail-summary-vector (make-vector rmail-total-messages nil)
2505	      rmail-msgref-vector (make-vector (1+ rmail-total-messages) nil))
2506
2507	(let ((i 0))
2508	  (while (<= i rmail-total-messages)
2509	    (aset rmail-msgref-vector i (list i))
2510	    (setq i (1+ i))))
2511	(let ((i 0))
2512	  (while (<= i rmail-total-messages)
2513	    (rmail-set-message-deleted-p i (rmail-message-attr-p i ".D"))
2514	    (setq i (1+ i))))
2515	(message "Counting messages...done")))))
2516
2517
2518(defsubst rmail-collect-deleted (message-end)
2519  "Collect the message deletion flags for each message.
2520MESSAGE-END is the buffer position corresponding to the end of
2521the message.  Point is at the beginning of the message."
2522  ;; NOTE: This piece of code will be executed on a per-message basis.
2523  ;; In the face of thousands of messages, it has to be as fast as
2524  ;; possible, hence some brute force constant use is employed in
2525  ;; addition to inlining.
2526  (save-excursion
2527    (setq deleted-head
2528	  (cons (if (and (search-forward (concat rmail-attribute-header ": ") message-end t)
2529			 (looking-at "\\?D"))
2530		    ?D
2531		  ?\s) deleted-head))))
2532
2533(defun rmail-set-message-counters-counter (&optional spot-to-find)
2534  "Collect the start positions of messages in list `messages-head'.
2535Return the number of messages after the one containing SPOT-TO-FIND."
2536  (let ((start (point))
2537	messages-after-spot)
2538    (while (search-backward "\n\nFrom " nil t)
2539      (forward-char 2)
2540      (when (looking-at rmail-unix-mail-delimiter)
2541	(if (and (<= (point) spot-to-find)
2542		 (null messages-after-spot))
2543	    (setq messages-after-spot total-messages))
2544	(rmail-collect-deleted start)
2545	(setq messages-head (cons (point-marker) messages-head)
2546	      total-messages (1+ total-messages)
2547	      start (point))
2548	;; Show progress after every 20 messages or so.
2549	(if (zerop (% total-messages 20))
2550	    (message "Counting messages...%d" total-messages))))
2551    ;; Handle the first message, maybe.
2552    (goto-char (point-min))
2553    (unless (not (looking-at rmail-unix-mail-delimiter))
2554      (if (and (<= (point) spot-to-find)
2555	       (null messages-after-spot))
2556	  (setq messages-after-spot total-messages))
2557      (rmail-collect-deleted start)
2558      (setq messages-head (cons (point-marker) messages-head)
2559	    total-messages (1+ total-messages)))
2560    messages-after-spot))
2561
2562;; Display a message.
2563
2564;;;; *** Rmail Message Formatting and Header Manipulation ***
2565
2566;; This is used outside of rmail.
2567(defun rmail-msg-is-pruned ()
2568  "Return nil if the current message is showing full headers."
2569  (with-current-buffer (if (rmail-buffers-swapped-p) rmail-view-buffer
2570                         rmail-buffer)
2571    (eq rmail-header-style 'normal)))
2572
2573(defun rmail-toggle-header (&optional arg)
2574  "Toggle between showing full and normal message headers.
2575With optional integer ARG, show the normal message header if ARG
2576is greater than zero; otherwise, show it in full."
2577  (interactive "P")
2578  (let ((rmail-header-style
2579	 (if (numberp arg)
2580	     (if (> arg 0) 'normal 'full)
2581           (if (rmail-msg-is-pruned) 'full 'normal))))
2582    (rmail-show-message)))
2583
2584(defun rmail-beginning-of-message ()
2585  "Show current message starting from the beginning."
2586  (interactive)
2587  (let ((rmail-show-message-hook '((lambda () (goto-char (point-min)))))
2588	(rmail-header-style (with-current-buffer (if (rmail-buffers-swapped-p)
2589						     rmail-view-buffer
2590						   rmail-buffer)
2591			      rmail-header-style)))
2592    (rmail-show-message rmail-current-message)))
2593
2594(defun rmail-end-of-message ()
2595  "Show bottom of current message."
2596  (interactive)
2597  (let ((rmail-show-message-hook '((lambda ()
2598				     (goto-char (point-max))
2599				     (recenter (1- (window-height))))))
2600	(rmail-header-style (with-current-buffer (if (rmail-buffers-swapped-p)
2601						     rmail-view-buffer
2602						   rmail-buffer)
2603			      rmail-header-style)))
2604    (rmail-show-message rmail-current-message)))
2605
2606(defun rmail-unknown-mail-followup-to ()
2607  "Handle a \"Mail-Followup-To\" header field with an unknown mailing list.
2608Ask the user whether to add that list name to `mail-mailing-lists'."
2609  ;; FIXME s-r not needed?  Use rmail-get-header?
2610  ;; We have not narrowed to the headers at ths point?
2611   (save-restriction
2612     (let ((mail-followup-to (mail-fetch-field "mail-followup-to" nil t)))
2613       (when mail-followup-to
2614	 (let ((addresses
2615		(split-string
2616		 (mail-strip-quoted-names mail-followup-to)
2617		 ",[[:space:]]+" t)))
2618	   (dolist (addr addresses)
2619	     (when (and (not (member addr mail-mailing-lists))
2620			(not
2621			 ;; taken from rmailsum.el
2622			 (string-match
2623			  (or rmail-user-mail-address-regexp
2624			      (concat "^\\("
2625				      (regexp-quote (user-login-name))
2626				      "\\($\\|@\\)\\|"
2627				      (regexp-quote user-mail-address)
2628				      "\\>\\)"))
2629			  addr))
2630			(y-or-n-p
2631			 (format-message "Add `%s' to `mail-mailing-lists'? "
2632					 addr)))
2633	       (customize-save-variable 'mail-mailing-lists
2634					(cons addr mail-mailing-lists)))))))))
2635
2636(defun rmail-widen ()
2637  "Display the entire mailbox file."
2638  (interactive)
2639  (rmail-swap-buffers-maybe)
2640  (widen))
2641
2642(defun rmail-no-mail-p ()
2643  "Return nil if there is mail, else \"No mail.\"."
2644  (if (zerop rmail-total-messages)
2645      (save-excursion
2646	;; Eg we deleted all the messages, so remove the old N/M mark.
2647	(with-current-buffer rmail-buffer (setq mode-line-process nil))
2648	(with-current-buffer rmail-view-buffer
2649	  (erase-buffer)
2650	  "No mail."))))
2651
2652(defun rmail-show-message (&optional n no-summary)
2653  "Show message number N (prefix argument), counting from start of file.
2654If summary buffer is currently displayed, update current message there also.
2655N defaults to the current message."
2656  (interactive "p")
2657  (or (eq major-mode 'rmail-mode)
2658      (switch-to-buffer rmail-buffer))
2659  ;; FIXME: Why do we swap the raw data back in?
2660  (rmail-swap-buffers-maybe)
2661  (rmail-maybe-set-message-counters)
2662  (widen)
2663  (let ((blurb (rmail-show-message-1 n)))
2664    (or (zerop rmail-total-messages)
2665	(progn
2666	  (when mail-mailing-lists
2667	    (rmail-unknown-mail-followup-to))
2668	  (if transient-mark-mode (deactivate-mark))
2669	  ;; If there is a summary buffer, try to move to this message
2670	  ;; in that buffer.  But don't complain if this message is
2671	  ;; not mentioned in the summary.  Don't do this at all if we
2672	  ;; were called on behalf of cursor motion in the summary
2673	  ;; buffer.
2674	  (and (rmail-summary-exists) (not no-summary)
2675	       (let ((curr-msg rmail-current-message))
2676		 (rmail-select-summary
2677		  (rmail-summary-goto-msg curr-msg t t))))
2678	  (with-current-buffer rmail-buffer
2679	    (rmail-auto-file))))
2680    (if blurb
2681	(message blurb))))
2682
2683(defun rmail-is-text-p ()
2684  "Return t if the region contains a text message, nil otherwise."
2685  (save-excursion
2686    (let ((text-regexp "\\(text\\|message\\)/")
2687	  (content-type-header (mail-fetch-field "content-type")))
2688      ;; The message is text if either there is no content type header
2689      ;; (a default of "text/plain; charset=US-ASCII" is assumed) or
2690      ;; the base content type is either text or message.
2691      (or (not content-type-header)
2692	  (and (string-match text-regexp content-type-header) t)))))
2693
2694(defcustom rmail-show-message-verbose-min 200000
2695  "Message size at which to show progress messages for displaying it."
2696  :type 'integer
2697  :group 'rmail
2698  :version "23.1")
2699
2700;; FIXME?
2701;; rmail-show-mime-function does not unquote >From lines.  Should it?
2702(defcustom rmail-mbox-format 'mboxrd
2703  "The mbox format that your system uses.
2704There is no way to determine this, so you should set the appropriate value.
2705The formats quote lines containing \"From \" differently.
2706The choices are:
2707  `mboxo' : lines that start with \"From \" quoted as \">From \"
2708  `mboxrd': lines that start with \">*From \" quoted with another \">\"
2709The `mboxo' format is ambiguous, in that one cannot know whether
2710a line starting with \">From \" originally had a \">\" or not.
2711
2712It is not critical to set this to the correct value; it only affects
2713how Rmail displays lines starting with \">*From \" in non-MIME messages.
2714
2715See also `unrmail-mbox-format'."
2716  :type '(choice (const mboxrd)
2717		 (const mboxro))
2718  :version "24.4"
2719  :group 'rmail-files)
2720
2721(defcustom rmail-show-message-set-modified nil
2722  "If non-nil, displaying an unseen message marks the Rmail buffer as modified."
2723  :type 'boolean
2724  :group 'rmail
2725  :version "28.1")
2726
2727(defun rmail-show-message-1 (&optional msg)
2728  "Show message MSG (default: current message) using `rmail-view-buffer'.
2729Return text to display in the minibuffer if MSG is out of
2730range (displaying a reasonable choice as well), nil otherwise.
2731The current mail message becomes the message displayed."
2732  (let ((mbox-buf rmail-buffer)
2733	(view-buf rmail-view-buffer)
2734	blurb beg end body-start coding-system character-coding
2735	is-text-message header-style
2736	showing-message)
2737    (if (not msg)
2738	(setq msg rmail-current-message))
2739    (unless (setq blurb (rmail-no-mail-p))
2740      (cond ((<= msg 0)
2741	     (setq msg 1
2742		   rmail-current-message 1
2743		   blurb "No previous message"))
2744	    ((> msg rmail-total-messages)
2745	     (setq msg rmail-total-messages
2746		   rmail-current-message rmail-total-messages
2747		   blurb "No following message"))
2748	    (t (setq rmail-current-message msg)))
2749      (with-current-buffer rmail-buffer
2750	(setq header-style rmail-header-style)
2751	;; Mark the message as seen, but preserve buffer modified flag.
2752	(let ((modiff (buffer-modified-p)))
2753	  (rmail-set-attribute rmail-unseen-attr-index nil)
2754          (and rmail-show-message-set-modified
2755               (setq modiff t))
2756	  (unless modiff
2757	    (restore-buffer-modified-p modiff)))
2758	;; bracket the message in the mail
2759	;; buffer and determine the coding system the transfer encoding.
2760	(rmail-swap-buffers-maybe)
2761	(setq beg (rmail-msgbeg msg)
2762	      end (rmail-msgend msg))
2763	(when (> (- end beg) rmail-show-message-verbose-min)
2764	  (setq showing-message t)
2765	  (message "Showing message %d..." msg))
2766	(narrow-to-region beg end)
2767	(goto-char beg)
2768	(with-current-buffer rmail-view-buffer
2769	  ;; We give the view buffer a buffer-local value of
2770	  ;; rmail-header-style based on the binding in effect when
2771          ;; this function is called; `rmail-toggle-header' can
2772	  ;; inspect this value to determine how to toggle.
2773          (setq-local rmail-header-style header-style)
2774          ;; In case viewing the previous message sets the paragraph
2775          ;; direction non-nil, we reset it here to allow independent
2776          ;; dynamic determination of paragraph direction in every
2777          ;; message.
2778          (setq bidi-paragraph-direction nil))
2779	(if (and rmail-enable-mime
2780		 rmail-show-mime-function
2781		 (re-search-forward "mime-version: 1.0" nil t))
2782	    (let ((rmail-buffer mbox-buf)
2783		  (rmail-view-buffer view-buf))
2784              (setq-local rmail-mime-decoded t)
2785	      (funcall rmail-show-mime-function))
2786	  (setq body-start (search-forward "\n\n" nil t))
2787	  (narrow-to-region beg (point))
2788	  (goto-char beg)
2789	  (save-excursion
2790	    (if (re-search-forward "^X-Coding-System: *\\(.*\\)$" nil t)
2791		(setq coding-system (intern (match-string 1)))
2792	      (setq coding-system (rmail-get-coding-system))))
2793	  (setq character-coding (mail-fetch-field "content-transfer-encoding")
2794		is-text-message (rmail-is-text-p))
2795	  (if character-coding
2796	      (setq character-coding (downcase character-coding)))
2797	  (narrow-to-region beg end)
2798	  ;; Decode the message body into an empty view buffer using a
2799	  ;; unibyte temporary buffer where the character decoding takes
2800	  ;; place.
2801	  (with-current-buffer rmail-view-buffer
2802	    (erase-buffer))
2803	  (if (null character-coding)
2804	      ;; Do it directly since that is fast.
2805	      (rmail-decode-region body-start end coding-system view-buf)
2806	    ;; Can this be done directly, skipping the temp buffer?
2807	    (with-temp-buffer
2808	      (set-buffer-multibyte nil)
2809	      (insert-buffer-substring mbox-buf body-start end)
2810	      (cond
2811	       ((string= character-coding "quoted-printable")
2812		;; See bug#5441.
2813		(or (mail-unquote-printable-region (point-min) (point-max)
2814						   nil t 'unibyte)
2815		    (message "Malformed MIME quoted-printable message")))
2816	       ((and (string= character-coding "base64") is-text-message)
2817		(condition-case err
2818		    (base64-decode-region (point-min) (point-max))
2819		  (error (message "%s" (cdr err)))))
2820	       ((eq character-coding 'uuencode)
2821		(error "uuencoded messages are not supported yet"))
2822	       (t))
2823	      (rmail-decode-region (point-min) (point-max)
2824				   coding-system view-buf)))
2825	  (with-current-buffer rmail-view-buffer
2826	    ;; Prepare the separator (blank line) before the body.
2827	    (goto-char (point-min))
2828	    (insert "\n")
2829	    ;; Unquote quoted From lines.
2830	    (let ((fromline (if (eq 'mboxrd rmail-mbox-format)
2831				"^>+From "
2832			      "^>From "))
2833		  case-fold-search)
2834	      (while (re-search-forward fromline nil t)
2835		(beginning-of-line)
2836		(delete-char 1)
2837		(forward-line)))
2838	    (goto-char (point-min)))
2839	  ;; Copy the headers to the front of the message view buffer.
2840	  (rmail-copy-headers beg end)
2841	  ;; Decode any RFC2047 encoded message headers.
2842	  (if rmail-enable-mime
2843	      (with-current-buffer rmail-view-buffer
2844		(rfc2047-decode-region
2845		 (point-min)
2846		 (progn
2847		   (search-forward "\n\n" nil 'move)
2848		   (point))))))
2849	;; highlight the message, activate any URL like text and add
2850	;; special highlighting for and quoted material.
2851	(with-current-buffer rmail-view-buffer
2852	  (goto-char (point-min))
2853	  (rmail-highlight-headers)
2854					;(rmail-activate-urls)
2855					;(rmail-process-quoted-material)
2856	  )
2857	;; Update the mode-line with message status information and swap
2858	;; the view buffer/mail buffer contents.
2859	(rmail-display-labels)
2860	(rmail-swap-buffers)
2861	(setq rmail-buffer-swapped t)
2862	(when showing-message
2863	  (setq blurb (format "Showing message %d...done" msg)))
2864	(run-hooks 'rmail-show-message-hook)))
2865    blurb))
2866
2867(defun rmail-copy-headers (beg _end &optional ignored-headers)
2868  "Copy displayed header fields to the message viewer buffer.
2869BEG and END marks the start and end positions of the message in
2870the mbox buffer.  If the optional argument IGNORED-HEADERS is
2871non-nil, ignore all header fields whose names match that regexp.
2872Otherwise, if `rmail-displayed-headers' is non-nil, copy only
2873those header fields whose names match that regexp.  Otherwise,
2874copy all header fields whose names do not match
2875`rmail-ignored-headers' (unless they also match
2876`rmail-nonignored-headers').  Moves point in the message viewer
2877buffer to the end of the headers."
2878  (let ((header-start-regexp "\n[^ \t]")
2879	lim)
2880    (with-current-buffer rmail-buffer
2881      (when (search-forward "\n\n" nil t)
2882	(forward-char -1)
2883	(save-restriction
2884	  ;; Put point right after the From header line.
2885	  (narrow-to-region beg (point))
2886	  (goto-char (point-min))
2887	  (unless (re-search-forward header-start-regexp nil t)
2888	    (rmail-error-bad-format))
2889	  (forward-char -1)
2890	  (cond
2891	   ;; Handle the case where all headers should be copied.
2892	   ((eq rmail-header-style 'full)
2893	    (prepend-to-buffer rmail-view-buffer beg (point-max))
2894	    ;; rmail-show-message-1 expects this function to leave point
2895	    ;; at the end of the headers.
2896
2897	    (let ((len (- (point-max) beg)))
2898	      (with-current-buffer rmail-view-buffer
2899		(goto-char (1+ len)))))
2900
2901	   ;; Handle the case where the headers matching the displayed
2902	   ;; headers regexp should be copied.
2903	   ((and rmail-displayed-headers (null ignored-headers))
2904	    (while (not (eobp))
2905	      (save-excursion
2906		(setq lim (if (re-search-forward header-start-regexp nil t)
2907			      (1+ (match-beginning 0))
2908			    (point-max))))
2909	      (when (looking-at rmail-displayed-headers)
2910		(append-to-buffer rmail-view-buffer (point) lim))
2911	      (goto-char lim)))
2912	   ;; Handle the ignored headers.
2913	   ((or ignored-headers (setq ignored-headers rmail-ignored-headers))
2914	    (while (and ignored-headers (not (eobp)))
2915	      (save-excursion
2916		(setq lim (if (re-search-forward header-start-regexp nil t)
2917			      (1+ (match-beginning 0))
2918			    (point-max))))
2919	      (if (and (looking-at ignored-headers)
2920		       (not (and rmail-nonignored-headers
2921				 (looking-at rmail-nonignored-headers))))
2922		  (goto-char lim)
2923		(append-to-buffer rmail-view-buffer (point) lim)
2924		(goto-char lim))))
2925	   (t (error "No headers selected for display!"))))))))
2926
2927(defun rmail-redecode-body (coding)
2928  "Decode the body of the current message using coding system CODING.
2929This is useful with mail messages that have malformed or missing
2930charset= headers.
2931
2932This function assumes that the current message is already decoded
2933and displayed in the RMAIL buffer, but the coding system used to
2934decode it was incorrect.  It then decodes the message again,
2935using the coding system CODING."
2936  (interactive "zCoding system for re-decoding this message: ")
2937  (when (not rmail-enable-mime)
2938    (with-current-buffer rmail-buffer
2939      (rmail-swap-buffers-maybe)
2940      (save-restriction
2941	(widen)
2942	(let ((msgbeg (rmail-msgbeg rmail-current-message))
2943	      (msgend (rmail-msgend rmail-current-message))
2944	      (buffer-read-only nil)
2945	      body-start x-coding-header old-coding)
2946	  (narrow-to-region msgbeg msgend)
2947	  (goto-char (point-min))
2948	  (unless (setq body-start (search-forward "\n\n" (point-max) 1))
2949	    (error "No message body"))
2950
2951	  (save-restriction
2952	    ;; Narrow to headers
2953	    (narrow-to-region (point-min) body-start)
2954	    (setq x-coding-header (goto-char (point-min)))
2955	    (if (not (re-search-forward "^X-Coding-System: *\\(.*\\)$" nil t))
2956		(setq old-coding (rmail-get-coding-system))
2957	      (setq old-coding (intern (match-string 1)))
2958	      (setq x-coding-header (point)))
2959	    (check-coding-system old-coding)
2960	    ;; Make sure the new coding system uses the same EOL
2961	    ;; conversion, to prevent ^M characters from popping up
2962	    ;; all over the place.
2963	    (let ((eol-type (coding-system-eol-type old-coding)))
2964	      (if (numberp eol-type)
2965		  (setq coding
2966			(coding-system-change-eol-conversion coding eol-type))))
2967	    (when (not (coding-system-equal
2968			(coding-system-base old-coding)
2969			(coding-system-base coding)))
2970	      ;; Rewrite the coding-system header.
2971	      (goto-char x-coding-header)
2972	      (if (> (point) (point-min))
2973		  (delete-region (line-beginning-position) (point))
2974		(forward-line)
2975		(insert "\n")
2976		(forward-line -1))
2977	      (insert "X-Coding-System: "
2978		      (symbol-name coding))))
2979	  (rmail-show-message))))))
2980
2981(defun rmail-highlight-headers ()
2982  "Highlight the headers specified by `rmail-highlighted-headers'.
2983Uses the face `rmail-highlight'."
2984  (if rmail-highlighted-headers
2985      (save-excursion
2986	(search-forward "\n\n" nil 'move)
2987	(save-restriction
2988	  (narrow-to-region (point-min) (point))
2989	  (let ((case-fold-search t)
2990		(inhibit-read-only t)
2991		(face 'rmail-highlight)
2992		;; List of overlays to reuse.
2993		(overlays rmail-overlay-list))
2994	    (goto-char (point-min))
2995	    (while (re-search-forward rmail-highlighted-headers nil t)
2996	      (skip-chars-forward " \t")
2997	      (let ((beg (point))
2998		    overlay)
2999		(while (progn (forward-line 1)
3000			      (looking-at "[ \t]")))
3001		;; Back up over newline, then trailing spaces or tabs
3002		(forward-char -1)
3003		(while (member (preceding-char) '(?  ?\t))
3004		  (forward-char -1))
3005		(if overlays
3006		    ;; Reuse an overlay we already have.
3007		    (progn
3008		      (setq overlay (car overlays)
3009			    overlays (cdr overlays))
3010		      (overlay-put overlay 'face face)
3011		      (move-overlay overlay beg (point)))
3012		  ;; Make a new overlay and add it to
3013		  ;; rmail-overlay-list.
3014		  (setq overlay (make-overlay beg (point)))
3015		  (overlay-put overlay 'face face)
3016		  (setq rmail-overlay-list
3017			(cons overlay rmail-overlay-list))))))))))
3018
3019(defun rmail-auto-file ()
3020  "Automatically move a message into another sfolder based on criteria.
3021This moves messages according to `rmail-automatic-folder-directives'.
3022It only does something in the folder that `rmail-file-name' specifies.
3023The function `rmail-show-message' calls this whenever it shows a message.
3024This leaves a message alone if it already has the `filed' attribute."
3025  (if (or (zerop rmail-total-messages)
3026	  (rmail-message-attr-p rmail-current-message "...F")
3027	  (not (string= (buffer-file-name)
3028			(expand-file-name rmail-file-name))))
3029      ;; Do nothing if the message has already been filed or if there
3030      ;; are no messages.
3031      nil
3032    ;; Find out some basics (common fields)
3033    (let ((from (mail-fetch-field "from"))
3034	  (subj (mail-fetch-field "subject"))
3035	  (to   (concat (mail-fetch-field "to") "," (mail-fetch-field "cc")))
3036	  (d rmail-automatic-folder-directives)
3037	  (directive-loop nil)
3038	  (folder nil))
3039      (while d
3040	(setq folder (car (car d))
3041	      directive-loop (cdr (car d)))
3042	(while (and (car directive-loop)
3043		    (let ((f (cond
3044			      ((string= (downcase (car directive-loop)) "from")
3045			       from)
3046			      ((string= (downcase (car directive-loop)) "to")
3047			       to)
3048			      ((string= (downcase (car directive-loop))
3049					"subject") subj)
3050			      (t (mail-fetch-field (car directive-loop))))))
3051		      ;; FIXME - shouldn't this ignore case?
3052		      (and f (string-match (car (cdr directive-loop)) f))))
3053	  (setq directive-loop (cdr (cdr directive-loop))))
3054	;; If there are no directives left, then it was a complete match.
3055	(if (null directive-loop)
3056	    (if (null folder)
3057		(rmail-delete-forward)
3058	      (if (string= "/dev/null" folder)
3059		  (rmail-delete-message)
3060		(rmail-output folder 1)
3061		(setq d nil))))
3062	(setq d (cdr d))))))
3063
3064;; Simple message motion commands.
3065
3066(defun rmail-next-message (n)
3067  "Show following message whether deleted or not.
3068With prefix arg N, moves forward N messages, or backward if N is negative."
3069  (interactive "p")
3070  (set-buffer rmail-buffer)
3071  (rmail-maybe-set-message-counters)
3072  (rmail-show-message (+ rmail-current-message n)))
3073
3074(defun rmail-previous-message (n)
3075  "Show previous message whether deleted or not.
3076With prefix arg N, moves backward N messages, or forward if N is negative."
3077  (interactive "p")
3078  (rmail-next-message (- n)))
3079
3080(defun rmail-next-undeleted-message (n)
3081  "Show following non-deleted message.
3082With prefix arg N, moves forward N non-deleted messages,
3083or backward if N is negative.
3084
3085Returns t if a new message is being shown, nil otherwise."
3086  (interactive "p")
3087  (set-buffer rmail-buffer)
3088  (rmail-maybe-set-message-counters)
3089  (let ((lastwin rmail-current-message)
3090	(current rmail-current-message))
3091    (while (and (> n 0) (< current rmail-total-messages))
3092      (setq current (1+ current))
3093      (if (not (rmail-message-deleted-p current))
3094	  (setq lastwin current n (1- n))))
3095    (while (and (< n 0) (> current 1))
3096      (setq current (1- current))
3097      (if (not (rmail-message-deleted-p current))
3098	  (setq lastwin current n (1+ n))))
3099    (if (/= lastwin rmail-current-message)
3100 	(progn (rmail-show-message lastwin)
3101 	       t)
3102      (if (< n 0)
3103	  (message "No previous nondeleted message"))
3104      (if (> n 0)
3105	  (message "No following nondeleted message"))
3106      nil)))
3107
3108(defun rmail-previous-undeleted-message (n)
3109  "Show previous non-deleted message.
3110With prefix argument N, moves backward N non-deleted messages,
3111or forward if N is negative."
3112  (interactive "p")
3113  (rmail-next-undeleted-message (- n)))
3114
3115(defun rmail-first-message ()
3116  "Show first message in file."
3117  (interactive)
3118  (rmail-maybe-set-message-counters)
3119  (rmail-show-message 1))
3120
3121(defun rmail-last-message ()
3122  "Show last message in file."
3123  (interactive)
3124  (rmail-maybe-set-message-counters)
3125  (rmail-show-message rmail-total-messages))
3126
3127(defun rmail-next-error-move (msg-pos _bad-marker)
3128  "Move to an error locus (probably grep hit) in an Rmail buffer.
3129MSG-POS is a marker pointing at the error message in the grep buffer.
3130BAD-MARKER is a marker that ought to point at where to move to,
3131but probably is garbage."
3132
3133  (let* ((message-loc (compilation--message->loc
3134		       (get-text-property msg-pos 'compilation-message
3135					  (marker-buffer msg-pos))))
3136	 (column (car message-loc))
3137	 (linenum (cadr message-loc))
3138	 line-text
3139	 pos
3140	 msgnum msgbeg msgend
3141	 header-field
3142	 line-number-within)
3143
3144    ;; Look at the whole Rmail file.
3145    (rmail-swap-buffers-maybe)
3146
3147    (save-restriction
3148      (widen)
3149      (save-excursion
3150	;; Find the line that the error message points at.
3151	(goto-char (point-min))
3152	(forward-line (1- linenum))
3153	(setq pos (point))
3154
3155	;; Find the text at the start of the line,
3156	;; before the first = sign.
3157	;; This text has a good chance of being also in the
3158	;; decoded message.
3159	(save-excursion
3160	  (skip-chars-forward "^=\n")
3161	  (setq line-text (buffer-substring pos (point))))
3162
3163	;; Find which message this position is in,
3164	;; and the limits of that message.
3165	(setq msgnum (rmail-what-message pos))
3166	(setq msgbeg (rmail-msgbeg msgnum))
3167	(setq msgend (rmail-msgend msgnum))
3168
3169	;; Find which header this locus is in,
3170	;; or if it's in the message body,
3171	;; and the line-based position within that.
3172	(goto-char msgbeg)
3173	(let ((header-end msgend))
3174	  (if (search-forward "\n\n" nil t)
3175	      (setq header-end (point)))
3176	  (if (>= pos header-end)
3177	      (setq line-number-within
3178		    (count-lines header-end pos))
3179	    (goto-char pos)
3180	    (unless (looking-at "^[^ \t]")
3181	      (re-search-backward "^[^ \t]"))
3182	    (looking-at "[^:\n]*[:\n]")
3183	    (setq header-field (match-string 0)
3184		  line-number-within (count-lines (point) pos))))))
3185
3186    ;; Display the right message.
3187    (rmail-show-message msgnum)
3188
3189    ;; Move to the right position within the displayed message.
3190    ;; Or at least try.  The decoded message's lines may not
3191    ;; correspond to the lines in the inbox file.
3192    (goto-char (point-min))
3193    (if header-field
3194	(progn
3195	  (re-search-forward (concat "^" (regexp-quote header-field)) nil t)
3196	  (forward-line line-number-within))
3197      (search-forward "\n\n" nil t)
3198      (if (re-search-forward (concat "^" (regexp-quote line-text)) nil t)
3199	  (goto-char (match-beginning 0))))
3200    (if (eobp)
3201	;; If the decoded message doesn't have enough lines,
3202	;; go to the beginning rather than the end.
3203	(goto-char (point-min))
3204      ;; Otherwise, go to the right column.
3205      (if column
3206	  (forward-char column)))))
3207
3208(defun rmail-what-message (&optional pos)
3209  "Return message number POS (or point) is in."
3210  (let* ((high rmail-total-messages)
3211         (mid (/ high 2))
3212         (low 1)
3213         (where (or pos
3214		    (with-current-buffer (if (rmail-buffers-swapped-p)
3215					     rmail-view-buffer
3216					   (current-buffer))
3217		      (point)))))
3218    (while (> (- high low) 1)
3219      (if (>= where (rmail-msgbeg mid))
3220          (setq low mid)
3221          (setq high mid))
3222      (setq mid (+ low (/ (- high low) 2))))
3223    (if (>= where (rmail-msgbeg high)) high low)))
3224
3225;; Searching in Rmail file.
3226
3227(defun rmail-search-message (msg regexp)
3228  "Return non-nil, if for message number MSG, regexp REGEXP matches."
3229  ;; This is adequate because its only caller, rmail-search,
3230  ;; unswaps the buffers.
3231  (goto-char (rmail-msgbeg msg))
3232  (if (and rmail-enable-mime
3233	   rmail-search-mime-message-function)
3234      (funcall rmail-search-mime-message-function msg regexp)
3235    (re-search-forward regexp (rmail-msgend msg) t)))
3236
3237(defvar rmail-search-last-regexp nil)
3238(defun rmail-search (regexp &optional n)
3239  "Show message containing next match for REGEXP (but not the current msg).
3240Prefix argument gives repeat count; negative argument means search
3241backwards (through earlier messages).
3242Interactively, empty argument means use same regexp used last time."
3243  (interactive
3244    (let* ((reversep (< (prefix-numeric-value current-prefix-arg) 0))
3245	   (prompt
3246	    (concat (if reversep "Reverse " "") "Rmail search (regexp"))
3247	   regexp)
3248      (setq prompt
3249	    (concat prompt
3250		    (if rmail-search-last-regexp
3251			(concat ", default "
3252				rmail-search-last-regexp "): ")
3253		      "): ")))
3254      (setq regexp (read-string prompt))
3255      (cond ((not (equal regexp ""))
3256	     (setq rmail-search-last-regexp regexp))
3257	    ((not rmail-search-last-regexp)
3258	     (error "No previous Rmail search string")))
3259      (list rmail-search-last-regexp
3260	    (prefix-numeric-value current-prefix-arg))))
3261  (or n (setq n 1))
3262  (message "%sRmail search for %s..."
3263	   (if (< n 0) "Reverse " "")
3264	   regexp)
3265  (set-buffer rmail-buffer)
3266  (let ((orig-message rmail-current-message)
3267	(msg rmail-current-message)
3268	(reversep (< n 0))
3269	(opoint (if (rmail-buffers-swapped-p) (point)))
3270	found)
3271    (rmail-swap-buffers-maybe)
3272    (rmail-maybe-set-message-counters)
3273    (widen)
3274    (unwind-protect
3275	(while (/= n 0)
3276	  ;; Check messages one by one, advancing message number up or
3277	  ;; down but searching forward through each message.
3278	  (if reversep
3279	      (while (and (null found) (> msg 1))
3280		(setq msg (1- msg)
3281		      found (rmail-search-message msg regexp)))
3282	    (while (and (null found) (< msg rmail-total-messages))
3283	      (setq msg (1+ msg)
3284		    found (rmail-search-message msg regexp))))
3285	  (setq n (+ n (if reversep 1 -1))))
3286      (if found
3287	  (progn
3288	    (rmail-show-message msg)
3289	    ;; Search forward (if this is a normal search) or backward
3290	    ;; (if this is a reverse search) through this message to
3291	    ;; position point.  This search may fail because REGEXP
3292	    ;; was found in the hidden portion of this message.  In
3293	    ;; that case, move point to the beginning of visible
3294	    ;; portion.
3295	    (if reversep
3296		(progn
3297		  (goto-char (point-max))
3298		  (re-search-backward regexp nil 'move))
3299	      (goto-char (point-min))
3300	      (re-search-forward regexp nil t))
3301	    (message "%sRmail search for %s...done"
3302		     (if reversep "Reverse " "")
3303		     regexp))
3304	(rmail-show-message orig-message)
3305	(if opoint (goto-char opoint))
3306	(ding)
3307	(message "Search failed: %s" regexp)))))
3308
3309(defun rmail-search-backwards (regexp &optional n)
3310  "Show message containing previous match for REGEXP.
3311Prefix argument gives repeat count; negative argument means search
3312forward (through later messages).
3313Interactively, empty argument means use same regexp used last time."
3314  (interactive
3315    (let* ((reversep (>= (prefix-numeric-value current-prefix-arg) 0))
3316	   (prompt
3317	    (concat (if reversep "Reverse " "") "Rmail search (regexp"))
3318	   regexp)
3319      (setq prompt
3320	    (concat prompt
3321		    (if rmail-search-last-regexp
3322			(concat ", default "
3323				rmail-search-last-regexp "): ")
3324		      "): ")))
3325      (setq regexp (read-string prompt))
3326      (cond ((not (equal regexp ""))
3327	     (setq rmail-search-last-regexp regexp))
3328	    ((not rmail-search-last-regexp)
3329	     (error "No previous Rmail search string")))
3330      (list rmail-search-last-regexp
3331	    (prefix-numeric-value current-prefix-arg))))
3332  (rmail-search regexp (- (or n 1))))
3333
3334;; Scan for attributes, and compare subjects.
3335
3336(defun rmail-first-unseen-message ()
3337  "Return message number of first message which has `unseen' attribute."
3338  (rmail-maybe-set-message-counters)
3339  (let ((current 1)
3340	found)
3341    (save-restriction
3342      (widen)
3343      (while (and (not found) (<= current rmail-total-messages))
3344	(if (rmail-message-attr-p current "......U")
3345	    (setq found current))
3346	(setq current (1+ current))))
3347    found))
3348
3349(defun rmail-simplified-subject (&optional msgnum)
3350  "Return the simplified subject of message MSGNUM (or current message).
3351Simplifying the subject means stripping leading and trailing
3352whitespace, replacing whitespace runs with a single space and
3353removing prefixes such as Re:, Fwd: and so on and mailing list
3354tags such as [tag]."
3355  (let ((subject (or (rmail-get-header "Subject" msgnum) ""))
3356	(regexp "\\`[ \t\n]*\\(\\(\\w\\{1,4\\}\u00a0*[::]\\|\\[[^]]+]\\)[ \t\n]+\\)*"))
3357    ;; Corporate mailing systems sometimes add `[External] :'; if that happened,
3358    ;; delete everything up thru there.  Empirically, that deletion makes
3359    ;; the Subject match the other messages in the thread.
3360    (if (string-match "\\[external][ \t\n]*:" subject)
3361        (setq subject (substring subject (match-end 0))))
3362    (setq subject (rfc2047-decode-string subject))
3363    (setq subject (replace-regexp-in-string regexp "" subject))
3364    (replace-regexp-in-string "[ \t\n]+" " " subject)))
3365
3366(defun rmail-simplified-subject-regexp ()
3367  "Return a regular expression matching the current simplified subject.
3368The idea is to match it against simplified subjects of other messages."
3369  (let ((subject (rmail-simplified-subject)))
3370    (setq subject (regexp-quote subject))
3371    ;; Hide commas so it will work ok if parsed as a comma-separated list
3372    ;; of regexps.
3373    (setq subject
3374	  (string-replace "," "\054" subject))
3375    (concat "\\`" subject "\\'")))
3376
3377(defun rmail-next-same-subject (n)
3378  "Go to the next mail message having the same subject header.
3379With prefix argument N, do this N times.
3380If N is negative, go backwards instead."
3381  (interactive "p")
3382  (let ((subject (rmail-simplified-subject))
3383	(forward (> n 0))
3384	(i rmail-current-message)
3385	found)
3386    (while (and (/= n 0)
3387		(if forward
3388		    (< i rmail-total-messages)
3389		  (> i 1)))
3390      (let (done)
3391	(while (and (not done)
3392		    (if forward
3393			(< i rmail-total-messages)
3394		      (> i 1)))
3395	  (setq i (if forward (1+ i) (1- i)))
3396	  (setq done (string-equal subject (rmail-simplified-subject i))))
3397	(if done (setq found i)))
3398      (setq n (if forward (1- n) (1+ n))))
3399    (if found
3400	(rmail-show-message found)
3401      (error "No %s message with same subject"
3402	     (if forward "following" "previous")))))
3403
3404(defun rmail-previous-same-subject (n)
3405  "Go to the previous mail message having the same subject header.
3406With prefix argument N, do this N times.
3407If N is negative, go forwards instead."
3408  (interactive "p")
3409  (rmail-next-same-subject (- n)))
3410
3411;;;; *** Rmail Message Deletion Commands ***
3412
3413(defun rmail-message-deleted-p (n)
3414  "Return non-nil if message number N is deleted (in `rmail-deleted-vector')."
3415  (= (aref rmail-deleted-vector n) ?D))
3416
3417(defun rmail-set-message-deleted-p (n state)
3418  "Set the deleted state of message number N (in `rmail-deleted-vector').
3419STATE non-nil means mark as deleted."
3420  (aset rmail-deleted-vector n (if state ?D ?\s)))
3421
3422(defun rmail-delete-message ()
3423  "Delete this message and stay on it."
3424  (interactive)
3425  (rmail-set-attribute rmail-deleted-attr-index t)
3426  (run-hooks 'rmail-delete-message-hook)
3427  (let ((del-msg rmail-current-message))
3428    (if (rmail-summary-exists)
3429	(rmail-select-summary
3430	 (rmail-summary-mark-deleted del-msg)))))
3431
3432(defun rmail-undelete-previous-message (count)
3433  "Back up to deleted message, select it, and undelete it."
3434  (interactive "p")
3435  (set-buffer rmail-buffer)
3436  (dotimes (_ count)
3437    (let ((msg rmail-current-message))
3438      (while (and (> msg 0)
3439                  (not (rmail-message-deleted-p msg)))
3440        (setq msg (1- msg)))
3441      (if (= msg 0)
3442          (error "No previous deleted message")
3443        (if (/= msg rmail-current-message)
3444            (rmail-show-message msg))
3445        (rmail-set-attribute rmail-deleted-attr-index nil)
3446        (if (rmail-summary-exists)
3447            (with-current-buffer rmail-summary-buffer
3448              (rmail-summary-mark-undeleted msg))))))
3449  (rmail-maybe-display-summary))
3450
3451(defun rmail-delete-forward (&optional count)
3452  "Delete this message and move to next nondeleted one.
3453Deleted messages stay in the file until the \\[rmail-expunge] command is given.
3454Optional argument COUNT (interactively, prefix argument) is a repeat count;
3455negative argument means move backwards instead of forwards.
3456
3457Returns t if a new message is displayed after the delete, or nil otherwise."
3458  (interactive "p")
3459  (if (not count) (setq count 1))
3460  (let (value backward)
3461    (if (< count 0)
3462	(setq count (- count) backward t))
3463    (dotimes (_ count)
3464      (rmail-set-attribute rmail-deleted-attr-index t)
3465      (run-hooks 'rmail-delete-message-hook)
3466      (let ((del-msg rmail-current-message))
3467	(if (rmail-summary-exists)
3468	    (rmail-select-summary
3469	     (rmail-summary-mark-deleted del-msg)))
3470	(setq value (rmail-next-undeleted-message (if backward -1 1)))))
3471    (rmail-maybe-display-summary)
3472    value))
3473
3474(defun rmail-delete-backward (&optional count)
3475  "Delete this message and move to previous nondeleted one.
3476Deleted messages stay in the file until the \\[rmail-expunge] command is given.
3477Optional argument COUNT (interactively, prefix argument) is a repeat count;
3478negative argument means move forwards instead of backwards.
3479
3480Returns t if a new message is displayed after the delete, or nil otherwise."
3481
3482  (interactive "p")
3483  (if (not count) (setq count 1))
3484  (rmail-delete-forward (- count)))
3485
3486;; Expunging.
3487
3488;; Compute the message number a given message would have after expunging.
3489;; The present number of the message is OLDNUM.
3490;; DELETEDVEC should be rmail-deleted-vector.
3491;; The value is nil for a message that would be deleted.
3492(defun rmail-msg-number-after-expunge (deletedvec oldnum)
3493  (if (or (null oldnum) (= (aref deletedvec oldnum) ?D))
3494      nil
3495    (let ((i 0)
3496	  (newnum 0))
3497      (while (< i oldnum)
3498	(if (/= (aref deletedvec i) ?D)
3499	    (setq newnum (1+ newnum)))
3500	(setq i (1+ i)))
3501      newnum)))
3502
3503(defun rmail-expunge-confirmed ()
3504  "Return t if expunge is needed and desirable.
3505If `rmail-confirm-expunge' is non-nil, ask user to confirm."
3506  (set-buffer rmail-buffer)
3507  (and (stringp rmail-deleted-vector)
3508       (string-match "D" rmail-deleted-vector)
3509       (if rmail-confirm-expunge
3510	   (and (funcall rmail-confirm-expunge
3511			 "Erase deleted messages from Rmail file? ")
3512		;; In case r-c-e's function returns non-nil, non-t
3513		t)
3514	 t)))
3515
3516(defun rmail-only-expunge (&optional dont-show)
3517  "Actually erase all deleted messages in the file."
3518  (interactive)
3519  (rmail-swap-buffers-maybe)
3520  (set-buffer rmail-buffer)
3521  (message "Expunging deleted messages...")
3522  ;; Discard all undo records for this buffer.
3523  (or (eq buffer-undo-list t)
3524      (setq buffer-undo-list nil))
3525  (rmail-maybe-set-message-counters)
3526  (let* ((omax (- (buffer-size) (point-max)))
3527	 (omin (- (buffer-size) (point-min)))
3528	 (opoint (if (and (> rmail-current-message 0)
3529			  (rmail-message-deleted-p rmail-current-message))
3530		     0
3531		   (if rmail-enable-mime
3532		       (with-current-buffer rmail-view-buffer
3533			 (- (point)(point-min)))
3534		     (- (point) (point-min)))))
3535	 (messages-head (cons (aref rmail-message-vector 0) nil))
3536	 (messages-tail messages-head)
3537	 ;; Don't make any undo records for the expunging.
3538	 (buffer-undo-list t)
3539	 (win))
3540    (unwind-protect
3541	(save-excursion
3542	  (widen)
3543	  (goto-char (point-min))
3544	  (let ((counter 0)
3545		(number 1)
3546		new-summary
3547		(new-msgref (list (list 0)))
3548		(buffer-read-only nil)
3549		(total rmail-total-messages)
3550		(new-message-number rmail-current-message)
3551		(messages rmail-message-vector)
3552		(deleted rmail-deleted-vector)
3553		(summary rmail-summary-vector))
3554	    (setq rmail-total-messages nil
3555		  rmail-current-message nil
3556		  rmail-message-vector nil
3557		  rmail-deleted-vector nil
3558		  rmail-summary-vector nil)
3559
3560	    (while (<= number total)
3561	      (if (= (aref deleted number) ?D)
3562		  (progn
3563		    (delete-region (aref messages number)
3564				   (aref messages (1+ number)))
3565		    (move-marker (aref messages number) nil)
3566		    (if (> new-message-number counter)
3567			(setq new-message-number (1- new-message-number))))
3568		(setq counter (1+ counter))
3569		(setq messages-tail
3570		      (setcdr messages-tail
3571			      (cons (aref messages number) nil)))
3572		(setq new-summary
3573		      (cons (if (= counter number) (aref summary (1- number)))
3574			    new-summary))
3575		(setq new-msgref
3576		      (cons (aref rmail-msgref-vector number)
3577			    new-msgref))
3578		(setcar (car new-msgref) counter))
3579	      (if (zerop (% (setq number (1+ number)) 20))
3580		  (message "Expunging deleted messages...%d" number)))
3581	    (setq messages-tail
3582		  (setcdr messages-tail
3583			  (cons (aref messages number) nil)))
3584	    (setq rmail-current-message new-message-number
3585		  rmail-total-messages counter
3586		  rmail-message-vector (apply 'vector messages-head)
3587		  rmail-deleted-vector (make-string (1+ counter) ?\s)
3588		  rmail-summary-vector (vconcat (nreverse new-summary))
3589		  rmail-msgref-vector (apply 'vector (nreverse new-msgref))
3590		  win t)))
3591      (message "Expunging deleted messages...done")
3592      (if (not win)
3593	  (narrow-to-region (- (buffer-size) omin) (- (buffer-size) omax)))
3594      (if (not dont-show)
3595	  (rmail-show-message (min rmail-current-message rmail-total-messages)))
3596      (if rmail-enable-mime
3597	  (goto-char (+ (point-min) opoint))
3598	(goto-char (+ (point) opoint))))))
3599
3600;; The DONT-SHOW argument is new in 23.  Does not seem very important.
3601(defun rmail-expunge (&optional dont-show)
3602  "Erase deleted messages from Rmail file and summary buffer.
3603This always shows a message (so as not to leave the Rmail buffer
3604unswapped), and always updates any summary (so that it remains
3605consistent with the Rmail buffer).  If DONT-SHOW is non-nil, it
3606does not pop any summary buffer."
3607  (interactive)
3608  (when (rmail-expunge-confirmed)
3609    (rmail-modify-format)
3610    (let ((was-deleted (rmail-message-deleted-p rmail-current-message))
3611	  (was-swapped (rmail-buffers-swapped-p)))
3612      (rmail-only-expunge t)
3613      ;; We always update the summary buffer, so that the contents
3614      ;; remain consistent with the rmail buffer.
3615      ;; The only difference is, in the dont-show case, we use a
3616      ;; cut-down version of rmail-select-summary that does not pop
3617      ;; the summary buffer.  It's only used by rmail-quit, which is
3618      ;; just going to bury any summary immediately after.  If we made
3619      ;; rmail-quit bury the summary first, dont-show could be removed.
3620      ;; But the expunge might not be confirmed...
3621      (if (rmail-summary-exists)
3622	  (if dont-show
3623	      (let ((total rmail-total-messages))
3624		(with-current-buffer rmail-summary-buffer
3625		  (let ((rmail-total-messages total))
3626		    (rmail-update-summary))))
3627	    (rmail-select-summary (rmail-update-summary))))
3628      ;; We always show a message, because (rmail-only-expunge t)
3629      ;; leaves the rmail buffer unswapped.
3630      ;; If we expunged the current message, a new one is current now,
3631      ;; so show it.  If we weren't showing a message, show it.
3632      (if (or was-deleted (not was-swapped))
3633	  (rmail-show-message-1 rmail-current-message)
3634	;; We can just show the same message that was being shown before.
3635	(rmail-display-labels)
3636	(rmail-swap-buffers)
3637	(setq rmail-buffer-swapped t)))))
3638
3639;;;; *** Rmail Mailing Commands ***
3640
3641(defun rmail-yank-current-message (buffer)
3642  "Yank into the current buffer the current message of Rmail buffer BUFFER.
3643If BUFFER is swapped with its message viewer buffer, yank out of BUFFER.
3644If BUFFER is not swapped, yank out of its message viewer buffer."
3645  (with-current-buffer buffer
3646    (unless (rmail-buffers-swapped-p)
3647      (setq buffer rmail-view-buffer)))
3648  (insert-buffer-substring buffer)
3649  ;; If they yank the text of BUFFER, the encoding of BUFFER is a
3650  ;; better default for the reply message than the default value of
3651  ;; buffer-file-coding-system.
3652  (and (coding-system-equal (default-value 'buffer-file-coding-system)
3653			    buffer-file-coding-system)
3654       (setq buffer-file-coding-system
3655	     (coding-system-change-text-conversion
3656	      buffer-file-coding-system (coding-system-base
3657					 (with-current-buffer buffer
3658					   buffer-file-coding-system))))))
3659
3660(defun rmail-start-mail (&optional noerase to subject in-reply-to cc
3661				   replybuffer sendactions same-window
3662				   other-headers)
3663  (let ((switch-function
3664	 (cond (same-window nil)
3665	       (rmail-mail-new-frame 'switch-to-buffer-other-frame)
3666	       (t 'switch-to-buffer-other-window)))
3667	yank-action)
3668    (if replybuffer
3669	;; The function used here must behave like insert-buffer wrt
3670	;; point and mark (see doc of sc-cite-original).
3671	(setq yank-action
3672	      `(rmail-yank-current-message ,replybuffer)))
3673    (push (cons "cc" cc) other-headers)
3674    (push (cons "in-reply-to" in-reply-to) other-headers)
3675    (setq other-headers
3676          (mapcar (lambda (elt)
3677                    (cons (car elt) (if (stringp (cdr elt))
3678                                        (rfc2047-decode-string (cdr elt)))))
3679		  other-headers))
3680    (if (stringp to) (setq to (rfc2047-decode-string to)))
3681    (if (stringp in-reply-to)
3682	(setq in-reply-to (rfc2047-decode-string in-reply-to)))
3683    (if (stringp cc) (setq cc (rfc2047-decode-string cc)))
3684    (if (stringp subject) (setq subject (rfc2047-decode-string subject)))
3685    (prog1
3686	(compose-mail to subject other-headers noerase
3687		      switch-function yank-action sendactions
3688		      (if replybuffer `(rmail-mail-return ,replybuffer)))
3689      (if (eq switch-function 'switch-to-buffer-other-frame)
3690	  ;; This is not a standard frame parameter; nothing except
3691	  ;; sendmail.el looks at it.
3692	  (modify-frame-parameters (selected-frame)
3693				   '((mail-dedicated-frame . t)))))))
3694
3695(defun rmail-mail-return (&optional newbuf)
3696  "Try to return to Rmail from the mail window.
3697If optional argument NEWBUF is specified, it is the Rmail buffer
3698to switch to."
3699  (cond
3700   ;; If there is only one visible frame with no special handling,
3701   ;; consider deleting the mail window to return to Rmail.
3702   ((or (null (delq (selected-frame) (visible-frame-list)))
3703	(not (or (window-dedicated-p (frame-selected-window))
3704		 (and pop-up-frames (one-window-p))
3705		 (cdr (assq 'mail-dedicated-frame
3706			    (frame-parameters))))))
3707    (let (rmail-flag summary-buffer)
3708      (unless (one-window-p)
3709	(with-current-buffer
3710	    (window-buffer (next-window (selected-window) 'not))
3711	  (setq rmail-flag (eq major-mode 'rmail-mode))
3712	  (setq summary-buffer
3713		(and (boundp 'mail-bury-selects-summary)
3714		     mail-bury-selects-summary
3715		     (boundp 'rmail-summary-buffer)
3716		     rmail-summary-buffer
3717		     (buffer-name rmail-summary-buffer)
3718		     (not (get-buffer-window rmail-summary-buffer))
3719		     rmail-summary-buffer))))
3720      (cond ((null rmail-flag)
3721	     ;; If the Rmail buffer is not in the next window, switch
3722	     ;; directly to the Rmail buffer specified by NEWBUF.
3723	     (if (buffer-live-p newbuf)
3724		 (switch-to-buffer newbuf)))
3725	    ;; If the Rmail buffer is in the next window, switch to
3726	    ;; the summary buffer if `mail-bury-selects-summary' is
3727	    ;; non-nil.  Otherwise just delete this window.
3728	    (summary-buffer
3729	     (switch-to-buffer summary-buffer))
3730	    (t
3731	     (delete-window)))))
3732   ;; If the frame was probably made for this buffer, the user
3733   ;; probably wants to delete it now.
3734   ((display-multi-frame-p)
3735    (delete-frame))
3736   ;; The previous frame is where normally they have the Rmail buffer
3737   ;; displayed.
3738   (t (other-frame -1))))
3739
3740(defun rmail-mail ()
3741  "Send mail in another window.
3742While composing the message, use \\[mail-yank-original] to yank the
3743original message into it."
3744  (interactive)
3745  (rmail-start-mail nil nil nil nil nil rmail-buffer))
3746
3747;; FIXME should complain if there is nothing to continue.
3748(defun rmail-continue ()
3749  "Continue composing outgoing message previously being composed."
3750  (interactive)
3751  (rmail-start-mail t))
3752
3753(defun rmail-reply (just-sender)
3754  "Reply to the current message.
3755Normally include Cc: to all other recipients of original message;
3756prefix argument means ignore them.  While composing the reply,
3757use \\[mail-yank-original] to yank the original message into it."
3758  (interactive "P")
3759  (if (zerop rmail-current-message)
3760      (error "There is no message to reply to"))
3761  (let (from reply-to cc subject date to message-id references
3762	     ;; resent-to resent-cc resent-reply-to
3763	     (msgnum rmail-current-message))
3764    (rmail-apply-in-message
3765     rmail-current-message
3766     (lambda ()
3767       (let ((end (point-max))
3768             subheader)
3769         ;; Find the message's real header.
3770         (search-forward "\n\n" nil 'move)
3771         (narrow-to-region (point-min) (point))
3772
3773         (goto-char (point-min))
3774
3775         ;; If this is an encrypted message, search for other header fields
3776         ;; inside the encrypted part, and use them instead of the real header.
3777
3778         ;; First, find a From: field after a plausible section start.
3779         (when (and (search-forward "\nContent-Type: multipart/encrypted;\n" nil t)
3780                    (save-restriction
3781                      (narrow-to-region (point-min) end)
3782                      (and (search-forward "\nFrom: " nil t)
3783                           (setq subheader (point)))))
3784           ;; We found one, so widen up to end of message and go there.
3785           (narrow-to-region (point-min) end)
3786           (goto-char subheader)
3787
3788           ;; Find the start of the inner header.
3789           (search-backward "\n--")
3790           (forward-line 2)
3791
3792           ;; Find the end of it.
3793           (let ((subheader-start (point)))
3794             (goto-char subheader)
3795             (search-forward "\n\n" nil 'move)
3796             (narrow-to-region subheader-start (point))))
3797
3798         (setq from (mail-fetch-field "from")
3799               reply-to (or (mail-fetch-field "mail-reply-to" nil t)
3800                            (mail-fetch-field "reply-to" nil t)
3801                            from)
3802               subject (mail-fetch-field "subject")
3803               date (mail-fetch-field "date")
3804               message-id (mail-fetch-field "message-id")
3805               references (mail-fetch-field "references" nil nil t)
3806               ;; Bug#512.  It's inappropriate to reply to these addresses.
3807               ;;resent-reply-to (mail-fetch-field "resent-reply-to" nil t)
3808               ;;resent-cc (and (not just-sender)
3809               ;;   	    (mail-fetch-field "resent-cc" nil t))
3810               ;;resent-to (or (mail-fetch-field "resent-to" nil t) "")
3811               ;;resent-subject (mail-fetch-field "resent-subject")
3812               ;;resent-date (mail-fetch-field "resent-date")
3813               ;;resent-message-id (mail-fetch-field "resent-message-id")
3814               )
3815         (unless just-sender
3816           (if (mail-fetch-field "mail-followup-to" nil t)
3817               ;; If this header field is present, use it instead of the
3818               ;; To and Cc fields.
3819               (setq to (mail-fetch-field "mail-followup-to" nil t))
3820             (setq cc (or (mail-fetch-field "cc" nil t) "")
3821                   to (or (mail-fetch-field "to" nil t) "")))))))
3822    ;; Merge the resent-to and resent-cc into the to and cc.
3823    ;; Bug#512.  It's inappropriate to reply to these addresses.
3824    ;;(if (and resent-to (not (equal resent-to "")))
3825    ;;    (setq to (if (not (equal to ""))
3826    ;;                 (concat to ", " resent-to)
3827    ;;               resent-to)))
3828    ;;(if (and resent-cc (not (equal resent-cc "")))
3829    ;;    (setq cc (if (not (equal cc ""))
3830    ;;                 (concat cc ", " resent-cc)
3831    ;;               resent-cc)))
3832    ;; Add `Re: ' to subject if not there already.
3833    (and (stringp subject)
3834	 (setq subject (rfc2047-decode-string subject)
3835	       subject
3836	       (concat rmail-reply-prefix
3837		       (if (let ((case-fold-search t))
3838			     (string-match rmail-reply-regexp subject))
3839			   (substring subject (match-end 0))
3840			 subject))))
3841    (rmail-start-mail
3842     nil
3843     ;; Using mail-strip-quoted-names is undesirable with newer mailers
3844     ;; since they can handle the names unstripped.
3845     ;; I don't know whether there are other mailers that still
3846     ;; need the names to be stripped.
3847;;;     (mail-strip-quoted-names reply-to)
3848     ;; Remove unwanted names from reply-to, since Mail-Followup-To
3849     ;; header causes all the names in it to wind up in reply-to, not
3850     ;; in cc.  But if what's left is an empty list, use the original.
3851     (let* ((reply-to-list (mail-dont-reply-to reply-to)))
3852       (if (string= reply-to-list "") reply-to reply-to-list))
3853     subject
3854     (rmail-make-in-reply-to-field from date message-id)
3855     (if just-sender
3856	 nil
3857       ;; `mail-dont-reply-to' doesn't need `mail-strip-quoted-names'.
3858       (let* ((cc-list (mail-dont-reply-to
3859			(mail-strip-quoted-names
3860			 (if (null cc) to (concat to ", " cc))))))
3861	 (if (string= cc-list "") nil cc-list)))
3862     rmail-buffer
3863     (list (list 'rmail-mark-message
3864		 rmail-buffer
3865		 (with-current-buffer rmail-buffer
3866		   (aref rmail-msgref-vector msgnum))
3867		 rmail-answered-attr-index))
3868     nil
3869     (if (or references message-id)
3870	 (list (cons "References" (if references
3871				      (concat
3872				       (mapconcat 'identity references " ")
3873				       " " message-id)
3874				    message-id)))))))
3875
3876(defun rmail-mark-message (buffer msgnum-list attribute)
3877  "Give BUFFER's message number in MSGNUM-LIST the attribute ATTRIBUTE.
3878This is use in the send-actions for message buffers.
3879MSGNUM-LIST is a list of the form (MSGNUM)
3880which is an element of rmail-msgref-vector."
3881  (with-current-buffer buffer
3882    (if (car msgnum-list)
3883	(rmail-set-attribute attribute t (car msgnum-list)))))
3884
3885(defun rmail-make-in-reply-to-field (from date message-id)
3886  (cond ((not from)
3887         (if message-id
3888             message-id
3889             nil))
3890        (mail-use-rfc822
3891         (require 'rfc822)
3892         (let ((tem (car (rfc822-addresses from))))
3893           (if message-id
3894               (if (or (not tem)
3895		       (string-match
3896			(regexp-quote (if (string-match "@[^@]*\\'" tem)
3897					  (substring tem 0
3898						     (match-beginning 0))
3899					tem))
3900			message-id))
3901                   ;; missing From, or Message-ID is sufficiently informative
3902                   message-id
3903		 (concat message-id " (" tem ")"))
3904	     ;; Message has no Message-ID field.
3905	     ;; Copy TEM, discarding text properties.
3906	     (setq tem (copy-sequence tem))
3907	     (set-text-properties 0 (length tem) nil tem)
3908	     (setq tem (copy-sequence tem))
3909	     ;; Use prin1 to fake RFC 822 (or later) quoting
3910	     (let ((field (prin1-to-string tem)))
3911	       ;; Wrap it in parens to make it a comment.
3912	       (if date
3913		   (concat "(" field "'s message of " date ")")
3914		 (concat "(" field ")"))))))
3915        ((let* ((foo "[^][\000-\037()<>@,;:\\\" ]+")
3916                (bar "[^][\000-\037()<>@,;:\\\"]+"))
3917	   ;; These strings both match all non-ASCII characters.
3918           (or (string-match (concat "\\`[ \t]*\\(" bar
3919                                     "\\)\\(<" foo "@" foo ">\\)?[ \t]*\\'")
3920                             ;; "Unix Loser <Foo@bar.edu>" => "Unix Loser"
3921                             from)
3922               (string-match (concat "\\`[ \t]*<" foo "@" foo ">[ \t]*(\\("
3923                                     bar "\\))[ \t]*\\'")
3924                             ;; "<Bugs@bar.edu>" (Losing Unix) => "Losing Unix"
3925                             from)))
3926         (let ((start (match-beginning 1))
3927               (end (match-end 1)))
3928           ;; Trim whitespace which above regexp match allows
3929           (while (and (< start end)
3930                       (memq (aref from start) '(?\t ?\s)))
3931             (setq start (1+ start)))
3932           (while (and (< start end)
3933                       (memq (aref from (1- end)) '(?\t ?\s)))
3934             (setq end (1- end)))
3935           (let ((field (substring from start end)))
3936             (if date (setq field (concat "message from " field " on " date)))
3937             (if message-id
3938                 ;; "<AA259@bar.edu> (message from Unix Loser on 1-Apr-89)"
3939                 (concat message-id " (" field ")")
3940	       ;; Wrap in parens to make it a comment.
3941	       (concat "(" field ")")))))
3942        (t
3943         ;; If we can't kludge it simply, do it correctly
3944         (let ((mail-use-rfc822 t))
3945           (rmail-make-in-reply-to-field from date message-id)))))
3946
3947(defun rmail-forward (resend)
3948  "Forward the current message to another user.
3949With prefix argument, \"resend\" the message instead of forwarding it;
3950see the documentation of `rmail-resend'."
3951  (interactive "P")
3952  (if (zerop rmail-current-message)
3953      (error "No message to forward"))
3954  (if resend
3955      (call-interactively 'rmail-resend)
3956    (let ((forward-buffer rmail-buffer)
3957	  (msgnum rmail-current-message)
3958	  (subject (concat "["
3959			   (let ((from (or (mail-fetch-field "From")
3960					   ;; FIXME - huh?
3961					   (mail-fetch-field ">From"))))
3962			     (if from
3963				 (concat (mail-strip-quoted-names from) ": ")
3964			       ""))
3965			   (or (mail-fetch-field "Subject") "")
3966			   "]")))
3967      (if (rmail-start-mail
3968	   nil nil subject nil nil rmail-buffer
3969	   (list (list 'rmail-mark-message
3970		       forward-buffer
3971		       (with-current-buffer rmail-buffer
3972			 (aref rmail-msgref-vector msgnum))
3973		       rmail-forwarded-attr-index))
3974	   ;; If only one window, use it for the mail buffer.
3975	   ;; Otherwise, use another window for the mail buffer
3976	   ;; so that the Rmail buffer remains visible
3977	   ;; and sending the mail will get back to it.
3978	   (and (not rmail-mail-new-frame) (one-window-p t)))
3979	  ;; The mail buffer is now current.
3980	  (save-excursion
3981	    ;; Insert after header separator--before signature if any.
3982	    (rfc822-goto-eoh)
3983	    (forward-line 1)
3984	    (if (and rmail-enable-mime rmail-enable-mime-composing
3985		     rmail-insert-mime-forwarded-message-function)
3986		(prog1
3987		    (funcall rmail-insert-mime-forwarded-message-function
3988			     forward-buffer)
3989		  ;; rmail-insert-mime-forwarded-message-function
3990		  ;; works by inserting MML tags into forward-buffer.
3991		  ;; The MUA will need to convert it to MIME before
3992		  ;; sending.  mail-encode-mml tells them to do that.
3993		  ;; message.el does that automagically.
3994		  (or (eq mail-user-agent 'message-user-agent)
3995		      (setq mail-encode-mml t)))
3996	      (insert "------- Start of forwarded message -------\n")
3997	      ;; Quote lines with `- ' if they start with `-'.
3998	      (let ((beg (point)) end)
3999		(setq end (point-marker))
4000		(set-marker-insertion-type end t)
4001		(insert-buffer-substring forward-buffer)
4002		(goto-char beg)
4003		(while (re-search-forward "^-" end t)
4004		  (beginning-of-line)
4005		  (insert "- ")
4006		  (forward-line 1))
4007		(goto-char end)
4008		(skip-chars-backward "\n")
4009		(if (< (point) end)
4010		    (forward-char 1))
4011		(delete-region (point) end)
4012		(set-marker end nil))
4013	      (insert "------- End of forwarded message -------\n"))
4014	    (push-mark))))))
4015
4016(defun rmail-resend (address &optional from comment mail-alias-file)
4017  "Resend current message to ADDRESSES.
4018ADDRESSES should be a single address, a string consisting of several
4019addresses separated by commas, or a list of addresses.
4020
4021Optional FROM is the address to resend the message from, and
4022defaults from the value of `user-mail-address'.
4023Optional COMMENT is a string to insert as a comment in the resent message.
4024Optional ALIAS-FILE is alternate aliases file to be used by sendmail,
4025typically for purposes of moderating a list."
4026  (interactive "sResend to: ")
4027  (require 'sendmail)
4028  (require 'mailalias)
4029  (unless (or (eq rmail-view-buffer (current-buffer))
4030	      (eq rmail-buffer (current-buffer)))
4031    (error "Not an Rmail buffer"))
4032  (if (not from) (setq from user-mail-address))
4033  (let ((tembuf (generate-new-buffer " sendmail temp"))
4034	(case-fold-search nil)
4035	(mail-personal-alias-file
4036	 (or mail-alias-file mail-personal-alias-file))
4037	(mailbuf rmail-buffer))
4038    (unwind-protect
4039	(with-current-buffer tembuf
4040	  ;;>> Copy message into temp buffer
4041	  (if (and rmail-enable-mime
4042		   rmail-insert-mime-resent-message-function)
4043                  (funcall rmail-insert-mime-resent-message-function mailbuf)
4044	    (insert-buffer-substring mailbuf))
4045	  (goto-char (point-min))
4046	  ;; Delete any Sender field, since that's not specifiable.
4047	  ; Only delete Sender fields in the actual header.
4048	  (re-search-forward "^$" nil 'move)
4049	  ; Using "while" here rather than "if" because some buggy mail
4050	  ; software may have inserted multiple Sender fields.
4051	  (while (re-search-backward "^Sender:" nil t)
4052	    (let (beg)
4053	      (setq beg (point))
4054	      (forward-line 1)
4055	      (while (looking-at "[ \t]")
4056		(forward-line 1))
4057	      (delete-region beg (point))))
4058	  ; Go back to the beginning of the buffer so the Resent- fields
4059	  ; are inserted there.
4060	  (goto-char (point-min))
4061	  ;;>> Insert resent-from:
4062	  (insert "Resent-From: " from "\n")
4063	  (insert "Resent-Date: " (mail-rfc822-date) "\n")
4064	  ;;>> Insert resent-to: and bcc if need be.
4065	  (let ((before (point)))
4066	    (if mail-self-blind
4067		(insert "Resent-Bcc: " (user-login-name) "\n"))
4068	    (insert "Resent-To: " (if (stringp address)
4069			       address
4070			     (mapconcat 'identity address ",\n\t"))
4071		    "\n")
4072	    ;; Expand abbrevs in the recipients.
4073	    (save-excursion
4074	      (if (featurep 'mailabbrev)
4075		  (let ((end (point-marker))
4076			(local-abbrev-table mail-abbrevs)
4077			(old-syntax-table (syntax-table)))
4078		    (if (and (not (vectorp mail-abbrevs))
4079			     (file-exists-p mail-personal-alias-file))
4080			(build-mail-abbrevs))
4081		    (unless mail-abbrev-syntax-table
4082		      (mail-abbrev-make-syntax-table))
4083		    (set-syntax-table mail-abbrev-syntax-table)
4084		    (goto-char before)
4085		    (while (and (< (point) end)
4086				(progn (forward-word-strictly 1)
4087				       (<= (point) end)))
4088		      (expand-abbrev))
4089		    (set-syntax-table old-syntax-table))
4090		(expand-mail-aliases before (point)))))
4091	  ;;>> Set up comment, if any.
4092	  (if (and (sequencep comment) (not (zerop (length comment))))
4093	      (let ((before (point))
4094		    after)
4095		(insert comment)
4096		(or (eolp) (insert "\n"))
4097		(setq after (point))
4098		(goto-char before)
4099		(while (< (point) after)
4100		  (insert "Resent-Comment: ")
4101		  (forward-line 1))))
4102	  ;; Don't expand aliases in the destination fields
4103	  ;; of the original message.
4104	  (let (mail-aliases)
4105	    (funcall send-mail-function)))
4106      (kill-buffer tembuf))
4107    (with-current-buffer rmail-buffer
4108      (rmail-set-attribute rmail-resent-attr-index t rmail-current-message))))
4109
4110(defvar mail-unsent-separator
4111  (concat "^ *---+ +Unsent message follows +---+ *$\\|"
4112	  "^ *---+ +Returned message +---+ *$\\|"
4113	  "^ *---+ *Returned mail follows *---+ *$\\|"
4114	  "^Start of returned message$\\|"
4115	  "^---+ Below this line is a copy of the message.$\\|"
4116	  "^ *---+ +Original message +---+ *$\\|"
4117	  "^ *--+ +begin message +--+ *$\\|"
4118	  "^ *---+ +Original message follows +---+ *$\\|"
4119	  "^ *---+ +Your message follows +---+ *$\\|"
4120	  "^|? *---+ +Message text follows: +---+ *|?$\\|"
4121          "^ *---+ +This is a copy of \\w+ message, including all the headers.*---+ *\n *---+ +The body of the message is [0-9]+ characters long; only the first *\n *---+ +[0-9]+ or so are included here\\. *$\\|"
4122	  "^ *---+ +This is a copy of \\w+ message, including all the headers.*---+ *$")
4123  "A regexp that matches the separator before the text of a failed message.")
4124
4125(defvar mail-mime-unsent-header "^Content-Type: message/rfc822 *$"
4126  "A regexp that matches the header of a MIME body part with a failed message.")
4127
4128(defun rmail-delete-headers (regexp)
4129  "Delete any mail headers matching REGEXP.
4130The message should be narrowed to just the headers."
4131  (when regexp
4132    (goto-char (point-min))
4133    (while (re-search-forward regexp nil t)
4134      (beginning-of-line)
4135      (delete-region (point)
4136		     (save-excursion
4137		       (if (re-search-forward "\n[^ \t]" nil t)
4138			   (1- (point))
4139			 (point-max)))))))
4140
4141(autoload 'mail-position-on-field "sendmail")
4142
4143(declare-function rmail-mime-toggle-raw "rmailmm" (&optional state))
4144
4145(defvar rmail-mime-mbox-buffer)
4146(defvar rmail-mime-view-buffer)
4147
4148(defun rmail-retry-failure ()
4149  "Edit a mail message which is based on the contents of the current message.
4150For a message rejected by the mail system, extract the interesting headers and
4151the body of the original message.
4152If the failed message is a MIME multipart message, it is searched for a
4153body part with a header which matches the variable `mail-mime-unsent-header'.
4154Otherwise, the variable `mail-unsent-separator' should match the string that
4155delimits the returned original message.
4156The variable `rmail-retry-ignored-headers' is a regular expression
4157specifying headers which should not be copied into the new message."
4158  (interactive)
4159  (require 'mail-utils)
4160  (let (bounce-buffer  ;; Buffer we found it in
4161        bounce-start   ;; Position of start of failed message in that buffer
4162        bounce-end     ;; Position of end of failed message in that buffer
4163        bounce-indent  ;; Number of columns we need to de-indent it.
4164	(msgnum rmail-current-message)
4165	resending
4166	(content-type (rmail-get-header "Content-Type")))
4167    (save-excursion
4168      (goto-char (point-min))
4169      (let ((case-fold-search t))
4170	(if (and content-type
4171		 (string-match
4172		  ";[\n\t ]*boundary=\"?\\([-0-9a-z'()+_,./:=? ]+\\)\"?"
4173		  content-type))
4174	    ;; Handle a MIME multipart bounce message
4175            ;; by scanning the raw buffer.
4176	    (let ((codestring
4177		   (concat "\n--"
4178			   (substring content-type (match-beginning 1)
4179				      (match-end 1))))
4180                  (beg (rmail-msgbeg msgnum))
4181                  (end (rmail-msgend msgnum)))
4182              (with-current-buffer rmail-view-buffer
4183                (save-restriction
4184                  (narrow-to-region beg end)
4185                  (goto-char (point-min))
4186	          (unless (re-search-forward mail-mime-unsent-header nil t)
4187		    (error "Cannot find beginning of header in failed message"))
4188	          (unless (search-forward "\n\n" nil t)
4189		    (error "Cannot find start of Mime data in failed message"))
4190	          (setq bounce-start (point))
4191                  (setq bounce-buffer (current-buffer))
4192	          (if (search-forward codestring nil t)
4193		      (setq bounce-end (match-beginning 0))
4194		    (setq bounce-end (point-max))))))
4195	  ;; Non-MIME bounce.
4196	  (or (re-search-forward mail-unsent-separator nil t)
4197	      (error "Cannot parse this as a failure message"))
4198	  (skip-chars-forward "\n")
4199	  ;; Support a style of failure message in which the original
4200	  ;; message is indented, and included within lines saying
4201	  ;; `Start of returned message' and `End of returned message'.
4202	  (if (looking-at " +Received:")
4203	      (progn
4204		(setq bounce-start (point))
4205		(skip-chars-forward " ")
4206		(setq bounce-indent (- (current-column)))
4207		(goto-char (point-max))
4208		(re-search-backward "^End of returned message$" nil t)
4209                (setq bounce-buffer (current-buffer))
4210		(setq bounce-end (point)))
4211	    ;; One message contained a few random lines before
4212	    ;; the old message header.  The first line of the
4213	    ;; message started with two hyphens.  A blank line
4214	    ;; followed these random lines.  The same line
4215	    ;; beginning with two hyphens was possibly marking
4216	    ;; the end of the message.
4217	    (if (looking-at "^--")
4218		(let ((boundary (buffer-substring-no-properties
4219				 (point)
4220				 (progn (end-of-line) (point)))))
4221		  (search-forward "\n\n")
4222		  (skip-chars-forward "\n")
4223		  (setq bounce-start (point))
4224		  (goto-char (point-max))
4225		  (search-backward (concat "\n\n" boundary) bounce-start t)
4226                  (setq bounce-buffer (current-buffer))
4227		  (setq bounce-end (point)))
4228	      (setq bounce-start (point)
4229                    bounce-buffer (current-buffer)
4230		    bounce-end (point-max)))
4231	    (unless (search-forward "\n\n" nil t)
4232	      (error "Cannot find end of header in failed message"))))))
4233    ;; We have found the message that bounced, within the current message.
4234    ;; Now start sending new message; default header fields from original.
4235    ;; Turn off the usual actions for initializing the message body
4236    ;; because we want to get only the text from the failure message.
4237    (let (mail-signature mail-setup-hook)
4238      (if (rmail-start-mail nil nil nil nil nil rmail-buffer
4239			    (list (list 'rmail-mark-message
4240					rmail-buffer
4241					(aref rmail-msgref-vector msgnum)
4242					rmail-retried-attr-index)))
4243	  ;; Insert original text as initial text of new draft message.
4244	  ;; Bind inhibit-read-only since the header delimiter
4245	  ;; of the previous message was probably read-only.
4246	  (let ((inhibit-read-only t)
4247		eoh)
4248	    (erase-buffer)
4249	    (insert-buffer-substring bounce-buffer
4250				     bounce-start bounce-end)
4251	    (goto-char (point-min))
4252	    (if bounce-indent
4253		(indent-rigidly (point-min) (point-max) bounce-indent))
4254	    (rfc822-goto-eoh)
4255	    (setq eoh (point))
4256	    (insert mail-header-separator)
4257	    (save-restriction
4258	      (narrow-to-region (point-min) eoh)
4259	      (rmail-delete-headers rmail-retry-ignored-headers)
4260	      (rmail-delete-headers "^\\(sender\\|return-path\\|received\\):")
4261	      (setq resending (mail-fetch-field "resent-to"))
4262	      (if mail-self-blind
4263		  (if resending
4264		      (insert "Resent-Bcc: " (user-login-name) "\n")
4265		    (insert "Bcc: " (user-login-name) "\n"))))
4266	    (goto-char (point-min))
4267	    (mail-position-on-field (if resending "Resent-To" "To") t))))))
4268
4269(defun rmail-summary-exists ()
4270  "Non-nil if in an RMAIL buffer and an associated summary buffer exists.
4271In fact, the non-nil value returned is the summary buffer itself."
4272  (and rmail-summary-buffer (buffer-name rmail-summary-buffer)
4273       rmail-summary-buffer))
4274
4275(defun rmail-summary-displayed ()
4276  "t if in RMAIL buffer and an associated summary buffer is displayed."
4277  (and rmail-summary-buffer (get-buffer-window rmail-summary-buffer)))
4278
4279(defcustom rmail-redisplay-summary nil
4280  "Non-nil means Rmail should show the summary when it changes.
4281This has an effect only if a summary buffer exists."
4282  :type 'boolean
4283  :group 'rmail-summary)
4284
4285(defcustom rmail-summary-window-size nil
4286  "Non-nil means specify the height for an Rmail summary window."
4287  :type '(choice (const :tag "Disabled" nil) integer)
4288  :group 'rmail-summary)
4289
4290;; Put the summary buffer back on the screen, if user wants that.
4291(defun rmail-maybe-display-summary ()
4292  (cond
4293   ((or (not rmail-summary-buffer)
4294	(not (buffer-name rmail-summary-buffer))))
4295   (rmail-redisplay-summary
4296    ;; If `rmail-redisplay-summary' is non-nil, make sure the summary
4297    ;; buffer is displayed.
4298    (display-buffer
4299     rmail-summary-buffer
4300     `(nil
4301       (reusable-frames . 0)
4302       ,(when rmail-summary-window-size
4303	  `(window-height . ,rmail-summary-window-size)))))
4304   (rmail-summary-window-size
4305    ;; If `rmail-summary-window-size' is non-nil and the summary buffer
4306    ;; is displayed, make sure it gets resized.
4307    (let ((window (get-buffer-window rmail-summary-buffer 0)))
4308      (when window
4309	(window-resize-no-error
4310	 window (- rmail-summary-window-size (window-height window))))))))
4311
4312;;;; *** Rmail Local Fontification ***
4313
4314(defun rmail-fontify-buffer-function ()
4315  ;; This function's symbol is bound to font-lock-fontify-buffer-function.
4316  (add-hook 'rmail-show-message-hook 'rmail-fontify-message nil t)
4317  ;; If we're already showing a message, fontify it now.
4318  (if rmail-current-message (rmail-fontify-message))
4319  ;; Prevent Font Lock mode from kicking in.
4320  (setq font-lock-fontified t))
4321
4322(defun rmail-unfontify-buffer-function ()
4323  ;; This function's symbol is bound to font-lock-fontify-unbuffer-function.
4324  (with-silent-modifications
4325    (save-restriction
4326      (widen)
4327      (remove-hook 'rmail-show-message-hook 'rmail-fontify-message t)
4328      (remove-text-properties (point-min) (point-max) '(rmail-fontified nil))
4329      (font-lock-default-unfontify-buffer))))
4330
4331(defun rmail-fontify-message ()
4332  ;; Fontify the current message if it is not already fontified.
4333  (if (text-property-any (point-min) (point-max) 'rmail-fontified nil)
4334      (with-silent-modifications
4335	(save-excursion
4336	  (save-match-data
4337	    (add-text-properties (point-min) (point-max) '(rmail-fontified t))
4338	    (font-lock-fontify-region (point-min) (point-max)))))))
4339
4340;;; Speedbar support for RMAIL files.
4341(defcustom rmail-speedbar-match-folder-regexp
4342  "\\`[A-Z0-9]+\\(\\.[A-Z0-9]+\\)?\\'"
4343  "Regexp matching Rmail folder names to be displayed in Speedbar.
4344Enabling this permits Speedbar to display your folders for easy
4345browsing, and moving of messages."
4346  :type 'regexp
4347  :group 'rmail
4348  :group 'speedbar)
4349
4350(defvar rmail-speedbar-last-user nil
4351  "The last user to be displayed in the speedbar.")
4352
4353(defvar rmail-speedbar-key-map nil
4354  "Keymap used when in rmail display mode.")
4355
4356(declare-function speedbar-make-specialized-keymap "speedbar" ())
4357
4358(defun rmail-install-speedbar-variables ()
4359  "Install those variables used by speedbar to enhance rmail."
4360  (unless rmail-speedbar-key-map
4361    (setq rmail-speedbar-key-map (speedbar-make-specialized-keymap))
4362    (define-key rmail-speedbar-key-map "e" 'speedbar-edit-line)
4363    (define-key rmail-speedbar-key-map "r" 'speedbar-edit-line)
4364    (define-key rmail-speedbar-key-map "\C-m" 'speedbar-edit-line)
4365    (define-key rmail-speedbar-key-map "M"
4366      'rmail-speedbar-move-message-to-folder-on-line)))
4367
4368;; Mouse-3.
4369(defvar rmail-speedbar-menu-items
4370  '(["Read Folder" speedbar-edit-line t]
4371    ["Move message to folder" rmail-speedbar-move-message-to-folder-on-line
4372     (save-excursion (beginning-of-line)
4373		     (looking-at "<M> "))])
4374  "Additional menu-items to add to speedbar frame.")
4375
4376(declare-function speedbar-insert-button "speedbar"
4377		  (text face mouse function &optional token prevline))
4378
4379;; Make sure our special speedbar major mode is loaded
4380(with-eval-after-load 'speedbar
4381  (rmail-install-speedbar-variables))
4382
4383(defun rmail-speedbar-buttons (buffer)
4384  "Create buttons for BUFFER containing rmail messages.
4385Click on the address under Reply to: to reply to this person.
4386Under Folders: Click a name to read it, or on the <M> to move the
4387current message into that RMAIL folder."
4388  (let ((from nil))
4389    (with-current-buffer buffer
4390      (goto-char (point-min))
4391      (if (not (re-search-forward "^Reply-To: " nil t))
4392	  (if (not (re-search-forward "^From:? " nil t))
4393	      (setq from t)))
4394      (if from
4395	  nil
4396	(setq from (buffer-substring (point) (line-end-position)))))
4397    (goto-char (point-min))
4398    (if (and (looking-at "Reply to:")
4399	     (equal from rmail-speedbar-last-user))
4400	nil
4401      (setq rmail-speedbar-last-user from)
4402      (erase-buffer)
4403      (insert "Reply To:\n")
4404      (if (stringp from)
4405	  (speedbar-insert-button from 'speedbar-directory-face 'highlight
4406				  'rmail-speedbar-button 'rmail-reply))
4407      (insert "Folders:\n")
4408      (let* ((case-fold-search nil)
4409	     (df (directory-files (with-current-buffer buffer
4410                                    default-directory)
4411				  nil rmail-speedbar-match-folder-regexp)))
4412	(dolist (file df)
4413	  (when (file-regular-p file)
4414	    (speedbar-insert-button "<M>" 'speedbar-button-face 'highlight
4415				    'rmail-speedbar-move-message file)
4416	    (speedbar-insert-button file 'speedbar-file-face 'highlight
4417				    'rmail-speedbar-find-file nil t)))))))
4418
4419(eval-when-compile (require 'dframe))
4420;; Part of the macro expansion of dframe-with-attached-buffer.
4421;; At runtime, will be pulled in as a require of speedbar.
4422(declare-function dframe-select-attached-frame "dframe" (&optional frame))
4423(declare-function dframe-maybee-jump-to-attached-frame "dframe" ())
4424
4425(defun rmail-speedbar-button (_text token _indent)
4426  "Execute an rmail command specified by TEXT.
4427The command used is TOKEN.  INDENT is not used."
4428  (dframe-with-attached-buffer
4429   (funcall token t)))
4430
4431(defun rmail-speedbar-find-file (text _token _indent)
4432  "Load in the rmail file TEXT.
4433TOKEN and INDENT are not used."
4434  (dframe-with-attached-buffer
4435   (message "Loading in RMAIL file %s..." text)
4436   (rmail text)))
4437
4438(declare-function speedbar-do-function-pointer "speedbar" ())
4439
4440(defun rmail-speedbar-move-message-to-folder-on-line ()
4441  "If the current line is a folder, move current message to it."
4442  (interactive)
4443  (save-excursion
4444    (beginning-of-line)
4445    (if (re-search-forward "<M> " (line-end-position) t)
4446	(progn
4447	  (forward-char -2)
4448	  (speedbar-do-function-pointer)))))
4449
4450(defun rmail-speedbar-move-message (_text token _indent)
4451  "From button TEXT, copy current message to the rmail file specified by TOKEN.
4452TEXT and INDENT are not used."
4453  (dframe-with-attached-buffer
4454   (message "Moving message to %s" token)
4455   ;; expand-file-name is needed due to the unhelpful way in which
4456   ;; rmail-output expands non-absolute filenames against rmail-default-file.
4457   ;; What is the point of that, anyway?
4458   (rmail-output (expand-file-name token))))
4459
4460;; Functions for setting, getting and encoding the POP password.
4461;; The password is encoded to prevent it from being easily accessible
4462;; to "prying eyes."  Obviously, this encoding isn't "real security,"
4463;; nor is it meant to be.
4464
4465;;;###autoload
4466(defun rmail-set-remote-password (password)
4467  "Set PASSWORD to be used for retrieving mail from a POP or IMAP server."
4468  (interactive "sPassword: ")
4469  (if password
4470      (setq rmail-encoded-remote-password
4471	    (rmail-encode-string password (emacs-pid)))
4472    (setq rmail-remote-password nil)
4473    (setq rmail-encoded-remote-password nil)))
4474
4475(defun rmail-get-remote-password (imap user host)
4476  "Get the password for retrieving mail from a POP or IMAP server.
4477If none has been set, the password is found via auth-source.  If
4478you use ~/.authinfo as your auth-source backend, then put
4479something like the following in that file:
4480
4481machine mymachine login myloginname password mypassword
4482
4483If auth-source search yields no result, prompt the user for the
4484password."
4485  (when (not rmail-encoded-remote-password)
4486    (if (not rmail-remote-password)
4487        (setq rmail-remote-password
4488              (let ((found (nth 0 (auth-source-search
4489                                   :max 1 :user user :host host
4490                                   :require '(:secret)))))
4491                (if found
4492                    (let ((secret (plist-get found :secret)))
4493                      (if (functionp secret)
4494                          (funcall secret)
4495                        secret))
4496                  (read-passwd (if imap
4497                                   "IMAP password: "
4498                                 "POP password: "))))))
4499    (rmail-set-remote-password rmail-remote-password)
4500    (setq rmail-remote-password nil))
4501  (rmail-encode-string rmail-encoded-remote-password (emacs-pid)))
4502
4503(defun rmail-have-password ()
4504  (or rmail-remote-password rmail-encoded-remote-password))
4505
4506(defun rmail-encode-string (string mask)
4507 "Encode STRING with integer MASK, by taking the exclusive OR of the
4508lowest byte in the mask with the first character of string, the
4509second-lowest-byte with the second character of the string, etc.,
4510restarting at the lowest byte of the mask whenever it runs out.
4511Returns the encoded string.  Calling the function again with an
4512encoded string (and the same mask) will decode the string."
4513 (setq mask (abs mask))			; doesn't work if negative
4514 (let* ((string-vector (string-to-vector string)) (i 0)
4515	(len (length string-vector)) (curmask mask) charmask)
4516   (while (< i len)
4517     (if (= curmask 0)
4518	 (setq curmask mask))
4519     (setq charmask (% curmask 256))
4520     (setq curmask (ash curmask -8))
4521     (aset string-vector i (logxor charmask (aref string-vector i)))
4522     (setq i (1+ i)))
4523   (concat string-vector)))
4524
4525(defun rmail-epa-decrypt-1 (mime)
4526  "Decrypt a single GnuPG encrypted text in a message.
4527The starting string of the encrypted text should have just been regexp-matched.
4528Argument MIME is non-nil if this is a mime message."
4529  (let* ((armor-start (match-beginning 0))
4530         (armor-prefix (buffer-substring
4531                        (line-beginning-position)
4532                        armor-start))
4533         (armor-end-regexp)
4534         armor-end after-end
4535         unquote)
4536    (if (string-match "<pre>\\'" armor-prefix)
4537        (setq armor-prefix ""))
4538
4539    (setq armor-end-regexp
4540          (concat "^"
4541                  armor-prefix
4542                  "-----END PGP MESSAGE-----$"))
4543    (setq armor-end (re-search-forward armor-end-regexp
4544                                       nil t))
4545
4546    (unless armor-end
4547      (error "Encryption armor beginning has no matching end"))
4548    (setq armor-start (move-marker (make-marker) armor-start))
4549    (setq armor-end (move-marker (make-marker) armor-end))
4550
4551    (goto-char armor-start)
4552
4553    ;; Because epa--find-coding-system-for-mime-charset not autoloaded.
4554    (require 'epa)
4555
4556    ;; Advance over this armor.
4557    (goto-char armor-end)
4558    (setq after-end (- (point-max) armor-end))
4559
4560    (when mime
4561      (save-excursion
4562        (goto-char armor-start)
4563        (re-search-backward "^--" nil t)
4564        (save-restriction
4565          (narrow-to-region (point) armor-start)
4566
4567          ;; Use the charset specified in the armor.
4568          (unless coding-system-for-read
4569            (if (re-search-forward "^[ \t]*Charset[ \t\n]*:[ \t\n]*\\(.*\\)" nil t)
4570                (setq coding-system-for-read
4571                      (epa--find-coding-system-for-mime-charset
4572                       (intern (downcase (match-string 1)))))))
4573
4574          (goto-char (point-min))
4575          (if (re-search-forward "^[ \t]*Content-transfer-encoding[ \t\n]*:[ \t\n]*quoted-printable[ \t]*$" nil t)
4576              (setq unquote t)))))
4577
4578    (when unquote
4579      (let ((inhibit-read-only t))
4580        (mail-unquote-printable-region armor-start
4581                                       (- (point-max) after-end))))
4582
4583    (condition-case nil
4584	(epa-decrypt-region
4585	 armor-start (- (point-max) after-end)
4586	 ;; Call back this function to prepare the output.
4587	 (lambda ()
4588	   (let ((inhibit-read-only t))
4589	     (delete-region armor-start (- (point-max) after-end))
4590	     (goto-char armor-start)
4591	     (current-buffer))))
4592      (error nil))
4593
4594    (list armor-start (- (point-max) after-end) mime
4595          armor-end-regexp
4596          (buffer-substring armor-start (- (point-max) after-end)))))
4597
4598(declare-function rmail-mime-entity-truncated "rmailmm" (entity))
4599
4600;; Should this have a key-binding, or be in a menu?
4601;; There doesn't really seem to be an appropriate menu.
4602;; Eg the edit command is not in a menu either.
4603
4604(defvar rmail-mime-render-html-function) ; defcustom in rmailmm
4605(defun rmail-epa-decrypt ()
4606  "Decrypt GnuPG or OpenPGP armors in current message."
4607  (interactive)
4608
4609  ;; Save the current buffer here for cleanliness, in case we
4610  ;; change it in one of the calls to `epa-decrypt-region'.
4611
4612  (save-excursion
4613    (let (decrypts
4614          (mime (and (eq major-mode 'rmail-mode) (rmail-mime-message-p)))
4615          mime-disabled)
4616      (goto-char (point-min))
4617
4618      ;; Turn off mime processing.
4619      (when (and mime
4620		 (not (get-text-property (point-min) 'rmail-mime-hidden)))
4621        (setq mime-disabled t)
4622	(rmail-mime))
4623
4624      ;; Now find all armored messages in the buffer
4625      ;; and decrypt them one by one.
4626      (goto-char (point-min))
4627      (while (re-search-forward "-----BEGIN PGP MESSAGE-----$" nil t)
4628	(let ((coding-system-for-read coding-system-for-read)
4629	      (case-fold-search t)
4630	      (armor-start (match-beginning 0)))
4631	  ;; Don't decrypt an armor that was copied into
4632	  ;; the message from a message it is a reply to.
4633	  (or (equal (buffer-substring (line-beginning-position)
4634				       armor-start)
4635		     "> ")
4636	      (push (rmail-epa-decrypt-1 mime) decrypts))))
4637
4638      (when (and decrypts (rmail-buffers-swapped-p))
4639	(when (y-or-n-p "Replace the original message? ")
4640          (when (eq major-mode 'rmail-mode)
4641            (rmail-add-label "decrypt"))
4642	  (setq decrypts (nreverse decrypts))
4643	  (let ((beg (rmail-msgbeg rmail-current-message))
4644		(end (rmail-msgend rmail-current-message)))
4645	    (with-current-buffer rmail-view-buffer
4646	      (narrow-to-region beg end)
4647	      (goto-char (point-min))
4648	      (dolist (d decrypts)
4649		;; Find, in the real Rmail buffer, the same armors
4650		;; that we found and decrypted in the view buffer.
4651		(if (re-search-forward "-----BEGIN PGP MESSAGE-----$" nil t)
4652		    (let (armor-start armor-end armor-end-regexp)
4653		      (setq armor-start (match-beginning 0)
4654			    armor-end-regexp (nth 3 d)
4655			    armor-end (re-search-forward
4656				       armor-end-regexp
4657				       nil t))
4658
4659		      ;; Found as expected -- now replace it with the decrypt.
4660		      (when armor-end
4661			(delete-region armor-start armor-end)
4662                        (insert (nth 4 d)))
4663
4664		      ;; Change the mime type (if this is in a mime part)
4665		      ;; so this part will display by default
4666		      ;; when the message is shown later.
4667		      (when (nth 2 d)
4668			(goto-char armor-start)
4669			(when (re-search-backward "^--" nil t)
4670			  (save-restriction
4671			    (narrow-to-region (point) armor-start)
4672			    (when (re-search-forward "^content-type[ \t\n]*:[ \t\n]*" nil t)
4673			      (when (looking-at "[^\n \t;]+")
4674				(let ((value (match-string 0)))
4675				  (unless (member value '("text/plain" "text/html"))
4676				    (replace-match "text/plain"))))))))
4677		      )))))))
4678
4679      (when (and (null decrypts)
4680                 mime mime-disabled)
4681        ;; Re-enable mime processing.
4682	(rmail-mime)
4683        ;; Find each Show button and show that part.
4684	(while (search-forward " Show " nil t)
4685	  (forward-char -2)
4686	  (let ((rmail-mime-render-html-function nil)
4687		(entity (get-text-property (point) 'rmail-mime-entity)))
4688            (unless (and (not (stringp entity))
4689                         (rmail-mime-entity-truncated entity))
4690              (push-button))))
4691        (goto-char (point-min))
4692        (while (re-search-forward "-----BEGIN PGP MESSAGE-----$" nil t)
4693          (let ((coding-system-for-read coding-system-for-read)
4694                (case-fold-search t))
4695            (push (rmail-epa-decrypt-1 mime) decrypts)))
4696
4697        )
4698
4699      (unless decrypts
4700	(error "Nothing to decrypt")))))
4701
4702
4703;;;;  Desktop support
4704
4705(defun rmail-restore-desktop-buffer (file-name
4706				     _buffer-name
4707				     _buffer-misc)
4708  "Restore an rmail buffer specified in a desktop file."
4709  (condition-case nil
4710      (progn
4711	(rmail-input file-name)
4712	(if (eq major-mode 'rmail-mode)
4713	    (current-buffer)
4714	  rmail-buffer))
4715    (file-locked
4716      (kill-buffer (current-buffer))
4717      nil)))
4718
4719(add-to-list 'desktop-buffer-mode-handlers
4720	     '(rmail-mode . rmail-restore-desktop-buffer))
4721
4722;; We use this to record the encoding of the current message before
4723;; saving the message collection.
4724(defvar rmail-message-encoding nil)
4725
4726;; Used in `write-region-annotate-functions' to write rmail files.
4727(defun rmail-write-region-annotate (start _end)
4728  (when (and (null start) rmail-buffer-swapped)
4729    (unless (buffer-live-p rmail-view-buffer)
4730      (error "Buffer `%s' with real text of `%s' has disappeared"
4731	     (buffer-name rmail-view-buffer)
4732	     (buffer-name (current-buffer))))
4733    (setq rmail-message-encoding buffer-file-coding-system)
4734    (set-buffer rmail-view-buffer)
4735    (widen)
4736    nil))
4737
4738;; Used to restore the encoding of the buffer where we show the
4739;; current message, after we save the message collection.  This is
4740;; needed because rmail-write-region-annotate switches buffers behind
4741;; save-file's back, with the side effect that last-coding-system-used
4742;; is assigned to buffer-file-coding-system of the wrong buffer.
4743(defun rmail-after-save-hook ()
4744  (if (or (eq rmail-view-buffer (current-buffer))
4745	  (eq rmail-buffer (current-buffer)))
4746      (with-current-buffer
4747	  (if (rmail-buffers-swapped-p) rmail-buffer rmail-view-buffer)
4748	(setq buffer-file-coding-system rmail-message-encoding))))
4749(add-hook 'after-save-hook 'rmail-after-save-hook)
4750
4751
4752(provide 'rmail)
4753
4754;;; rmail.el ends here
4755