Relicense "GPLv2 or later" files to "GPLv3 or later".
[gnus] / contrib / sendmail.el
1 ;;; sendmail.el --- mail sending commands for Emacs.  -*- byte-compile-dynamic: t -*-
2
3 ;; Copyright (C) 1985, 1986, 1992, 1993, 1994, 1995, 1996, 1998, 2000,
4 ;;   2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
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, or (at your option)
14 ;; 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; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;; This mode provides mail-sending facilities from within Emacs.  It is
29 ;; documented in the Emacs user's manual.
30
31 ;;; Code:
32 (eval-when-compile
33   ;; Necessary to avoid recursive `require's.
34   (provide 'sendmail)
35   (require 'rmail)
36   (require 'mailalias))
37
38 (autoload 'rfc2047-encode-string "rfc2047")
39
40 (defgroup sendmail nil
41   "Mail sending commands for Emacs."
42   :prefix "mail-"
43   :group 'mail)
44
45 (defcustom mail-setup-with-from t
46   "Non-nil means insert `From:' field when setting up the message."
47   :type 'boolean
48   :group 'sendmail
49   :version "22.1")
50
51 (defcustom sendmail-program
52   (cond
53     ((file-exists-p "/usr/sbin/sendmail") "/usr/sbin/sendmail")
54     ((file-exists-p "/usr/lib/sendmail") "/usr/lib/sendmail")
55     ((file-exists-p "/usr/ucblib/sendmail") "/usr/ucblib/sendmail")
56     (t "fakemail"))                     ;In ../etc, to interface to /bin/mail.
57   "Program used to send messages."
58   :group 'mail
59   :type 'file)
60
61 ;;;###autoload
62 (defcustom mail-from-style 'angles
63   "Specifies how \"From:\" fields look.
64
65 If `nil', they contain just the return address like:
66         king@grassland.com
67 If `parens', they look like:
68         king@grassland.com (Elvis Parsley)
69 If `angles', they look like:
70         Elvis Parsley <king@grassland.com>
71 If `system-default', allows the mailer to insert its default From field
72 derived from the envelope-from address.
73
74 In old versions of Emacs, the `system-default' setting also caused
75 Emacs to pass the proper email address from `user-mail-address'
76 to the mailer to specify the envelope-from address.  But that is now
77 controlled by a separate variable, `mail-specify-envelope-from'."
78   :type '(choice (const nil) (const parens) (const angles)
79                  (const system-default))
80   :version "20.3"
81   :group 'sendmail)
82
83 ;;;###autoload
84 (defcustom mail-specify-envelope-from nil
85   "If non-nil, specify the envelope-from address when sending mail.
86 The value used to specify it is whatever is found in
87 the variable `mail-envelope-from', with `user-mail-address' as fallback.
88
89 On most systems, specifying the envelope-from address is a
90 privileged operation.  This variable affects sendmail and
91 smtpmail -- if you use feedmail to send mail, see instead the
92 variable `feedmail-deduce-envelope-from'."
93   :version "21.1"
94   :type 'boolean
95   :group 'sendmail)
96
97 (defcustom mail-envelope-from nil
98   "If non-nil, designate the envelope-from address when sending mail.
99 This only has an effect if `mail-specify-envelope-from' is non-nil.
100 The value should be either a string, or the symbol `header' (in
101 which case the contents of the \"From\" header of the message
102 being sent is used), or nil (in which case the value of
103 `user-mail-address' is used)."
104   :version "21.1"
105   :type '(choice (string :tag "From-name")
106                  (const :tag "Use From: header from message" header)
107                  (const :tag "Use `user-mail-address'" nil))
108   :group 'sendmail)
109
110 ;;;###autoload
111 (defcustom mail-self-blind nil
112   "Non-nil means insert BCC to self in messages to be sent.
113 This is done when the message is initialized,
114 so you can remove or alter the BCC field to override the default."
115   :type 'boolean
116   :group 'sendmail)
117
118 ;;;###autoload
119 (defcustom mail-interactive nil
120   "Non-nil means when sending a message wait for and display errors.
121 nil means let mailer mail back a message to report errors."
122   :type 'boolean
123   :group 'sendmail)
124
125 (defcustom mail-yank-ignored-headers
126   (concat "^"
127           (regexp-opt '("via" "mail-from" "origin" "status" "remailed"
128                         "received" "message-id" "summary-line" "to" "subject"
129                         "in-reply-to" "return-path" "mail-reply-to"
130                         "mail-followup-to") "\\(?:")
131           ":")
132   "Delete these headers from old message when it's inserted in a reply."
133   :type 'regexp
134   :group 'sendmail)
135
136 ;; Prevent problems with `window-system' not having the correct value
137 ;; when loaddefs.el is loaded. `custom-reevaluate-setting' needs the
138 ;; standard value.
139 ;;;###autoload
140 (put 'send-mail-function 'standard-value
141      '((if (and window-system (memq system-type '(darwin windows-nt)))
142            'mailclient-send-it
143          'sendmail-send-it)))
144
145 ;; Useful to set in site-init.el
146 ;;;###autoload
147 (defcustom send-mail-function
148   (if (and window-system (memq system-type '(darwin windows-nt)))
149       'mailclient-send-it
150     'sendmail-send-it)
151   "Function to call to send the current buffer as mail.
152 The headers should be delimited by a line which is
153 not a valid RFC822 header or continuation line,
154 that matches the variable `mail-header-separator'.
155 This is used by the default mail-sending commands.  See also
156 `message-send-mail-function' for use with the Message package."
157   :type '(radio (function-item sendmail-send-it :tag "Use Sendmail package")
158                 (function-item smtpmail-send-it :tag "Use SMTPmail package")
159                 (function-item feedmail-send-it :tag "Use Feedmail package")
160                 (function-item mailclient-send-it :tag "Use Mailclient package")
161                 function)
162   :group 'sendmail)
163
164 ;;;###autoload
165 (defcustom mail-header-separator "--text follows this line--"
166   "Line used to separate headers from text in messages being composed."
167   :type 'string
168   :group 'sendmail)
169
170 ;; Set up mail-header-separator for use as a category text property.
171 (put 'mail-header-separator 'rear-nonsticky '(category))
172 ;; This was a nice idea, for preventing accidental modification of
173 ;; the separator.   But I found it also prevented or obstructed
174 ;; certain deliberate operations, such as copying the separator line
175 ;; up to the top to send myself a copy of an already sent outgoing message
176 ;; and other things.  So I turned it off.  --rms.
177 ;;(put 'mail-header-separator 'read-only t)
178
179 ;;;###autoload
180 (defcustom mail-archive-file-name nil
181   "Name of file to write all outgoing messages in, or nil for none.
182 This can be an inbox file or an Rmail file."
183   :type '(choice file (const nil))
184   :group 'sendmail)
185
186 ;;;###autoload
187 (defcustom mail-default-reply-to nil
188   "Address to insert as default Reply-to field of outgoing messages.
189 If nil, it will be initialized from the REPLYTO environment variable
190 when you first send mail."
191   :type '(choice (const nil) string)
192   :group 'sendmail)
193
194 ;;;###autoload
195 (defcustom mail-alias-file nil
196   "If non-nil, the name of a file to use instead of `/usr/lib/aliases'.
197 This file defines aliases to be expanded by the mailer; this is a different
198 feature from that of defining aliases in `.mailrc' to be expanded in Emacs.
199 This variable has no effect unless your system uses sendmail as its mailer."
200   :type '(choice (const nil) file)
201   :group 'sendmail)
202
203 ;;;###autoload
204 (defcustom mail-personal-alias-file "~/.mailrc"
205   "If non-nil, the name of the user's personal mail alias file.
206 This file typically should be in same format as the `.mailrc' file used by
207 the `Mail' or `mailx' program.
208 This file need not actually exist."
209   :type '(choice (const nil) file)
210   :group 'sendmail)
211
212 ;;;###autoload
213 (defcustom mail-setup-hook nil
214   "Normal hook, run each time a new outgoing mail message is initialized.
215 The function `mail-setup' runs this hook."
216   :type 'hook
217   :options '(fortune-to-signature spook mail-abbrevs-setup)
218   :group 'sendmail)
219
220 ;;;###autoload
221 (defvar mail-aliases t
222   "Alist of mail address aliases,
223 or t meaning should be initialized from your mail aliases file.
224 \(The file's name is normally `~/.mailrc', but `mail-personal-alias-file'
225 can specify a different file name.)
226 The alias definitions in the file have this form:
227     alias ALIAS MEANING")
228
229 (defvar mail-alias-modtime nil
230   "The modification time of your mail alias file when it was last examined.")
231
232 ;;;###autoload
233 (defcustom mail-yank-prefix nil
234   "Prefix insert on lines of yanked message being replied to.
235 nil means use indentation."
236   :type '(choice (const nil) string)
237   :group 'sendmail)
238
239 ;;;###autoload
240 (defcustom mail-indentation-spaces 3
241   "Number of spaces to insert at the beginning of each cited line.
242 Used by `mail-yank-original' via `mail-indent-citation'."
243   :type 'integer
244   :group 'sendmail)
245
246 (defvar mail-yank-hooks nil
247   "Obsolete hook for modifying a citation just inserted in the mail buffer.
248 Each hook function can find the citation between (point) and (mark t).
249 And each hook function should leave point and mark around the citation
250 text as modified.
251
252 This is a normal hook, misnamed for historical reasons.
253 It is semi-obsolete and mail agents should no longer use it.")
254
255 ;;;###autoload
256 (defcustom mail-citation-hook nil
257   "Hook for modifying a citation just inserted in the mail buffer.
258 Each hook function can find the citation between (point) and (mark t),
259 and should leave point and mark around the citation text as modified.
260 The hook functions can find the header of the cited message
261 in the variable `mail-citation-header', whether or not this is included
262 in the cited portion of the message.
263
264 If this hook is entirely empty (nil), a default action is taken
265 instead of no action."
266   :type 'hook
267   :group 'sendmail)
268
269 (defvar mail-citation-header nil
270   "While running `mail-citation-hook', this variable holds the message header.
271 This enables the hook functions to see the whole message header
272 regardless of what part of it (if any) is included in the cited text.")
273
274 ;;;###autoload
275 (defcustom mail-citation-prefix-regexp "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|[ \t]*"
276   "Regular expression to match a citation prefix plus whitespace.
277 It should match whatever sort of citation prefixes you want to handle,
278 with whitespace before and after; it should also match just whitespace.
279 The default value matches citations like `foo-bar>' plus whitespace."
280   :type 'regexp
281   :group 'sendmail
282   :version "20.3")
283
284 (defvar mail-abbrevs-loaded nil)
285 (defvar mail-mode-map
286   (let ((map (make-sparse-keymap)))
287     (define-key map "\M-\t" 'mail-complete)
288     (define-key map "\C-c?" 'describe-mode)
289     (define-key map "\C-c\C-f\C-t" 'mail-to)
290     (define-key map "\C-c\C-f\C-b" 'mail-bcc)
291     (define-key map "\C-c\C-f\C-f" 'mail-fcc)
292     (define-key map "\C-c\C-f\C-c" 'mail-cc)
293     (define-key map "\C-c\C-f\C-s" 'mail-subject)
294     (define-key map "\C-c\C-f\C-r" 'mail-reply-to)
295     (define-key map "\C-c\C-f\C-a" 'mail-mail-reply-to)    ; author
296     (define-key map "\C-c\C-f\C-l" 'mail-mail-followup-to) ; list
297     (define-key map "\C-c\C-t" 'mail-text)
298     (define-key map "\C-c\C-y" 'mail-yank-original)
299     (define-key map "\C-c\C-r" 'mail-yank-region)
300     (define-key map [remap split-line] 'mail-split-line)
301     (define-key map "\C-c\C-q" 'mail-fill-yanked-message)
302     (define-key map "\C-c\C-w" 'mail-signature)
303     (define-key map "\C-c\C-v" 'mail-sent-via)
304     (define-key map "\C-c\C-c" 'mail-send-and-exit)
305     (define-key map "\C-c\C-s" 'mail-send)
306     (define-key map "\C-c\C-i" 'mail-attach-file)
307
308     (define-key map [menu-bar mail]
309       (cons "Mail" (make-sparse-keymap "Mail")))
310
311     (define-key map [menu-bar mail fill]
312       '("Fill Citation" . mail-fill-yanked-message))
313
314     (define-key map [menu-bar mail yank]
315       '("Cite Original" . mail-yank-original))
316
317     (define-key map [menu-bar mail signature]
318       '("Insert Signature" . mail-signature))
319
320     (define-key map [menu-bar mail mail-sep]
321       '("--"))
322
323     (define-key map [menu-bar mail cancel]
324       '("Cancel" . mail-dont-send))
325
326     (define-key map [menu-bar mail send-stay]
327       '("Send, Keep Editing" . mail-send))
328
329     (define-key map [menu-bar mail send]
330       '("Send Message" . mail-send-and-exit))
331
332     (define-key map [menu-bar headers]
333       (cons "Headers" (make-sparse-keymap "Move to Header")))
334
335     (define-key map [menu-bar headers text]
336       '("Text" . mail-text))
337
338     (define-key map [menu-bar headers expand-aliases]
339       '("Expand Aliases" . expand-mail-aliases))
340
341     (define-key map [menu-bar headers sent-via]
342       '("Sent Via" . mail-sent-via))
343
344     (define-key map [menu-bar headers mail-reply-to]
345       '("Mail Reply To" . mail-mail-reply-to))
346
347     (define-key map [menu-bar headers mail-followup-to]
348       '("Mail Followup To" . mail-mail-followup-to))
349
350     (define-key map [menu-bar headers reply-to]
351       '("Reply-To" . mail-reply-to))
352
353     (define-key map [menu-bar headers bcc]
354       '("Bcc" . mail-bcc))
355
356     (define-key map [menu-bar headers fcc]
357       '("Fcc" . mail-fcc))
358
359     (define-key map [menu-bar headers cc]
360       '("Cc" . mail-cc))
361
362     (define-key map [menu-bar headers subject]
363       '("Subject" . mail-subject))
364
365     (define-key map [menu-bar headers to]
366       '("To" . mail-to))
367
368     map))
369
370 (autoload 'build-mail-aliases "mailalias"
371   "Read mail aliases from user's personal aliases file and set `mail-aliases'."
372   nil)
373
374 (autoload 'expand-mail-aliases "mailalias"
375   "Expand all mail aliases in suitable header fields found between BEG and END.
376 Suitable header fields are `To', `Cc' and `Bcc' and their `Resent-' variants.
377 Optional second arg EXCLUDE may be a regular expression defining text to be
378 removed from alias expansions."
379   nil)
380
381 ;;;###autoload
382 (defcustom mail-signature nil
383   "Text inserted at end of mail buffer when a message is initialized.
384 If t, it means to insert the contents of the file `mail-signature-file'.
385 If a string, that string is inserted.
386  (To make a proper signature, the string should begin with \\n\\n-- \\n,
387   which is the standard way to delimit a signature in a message.)
388 Otherwise, it should be an expression; it is evaluated
389 and should insert whatever you want to insert."
390   :type '(choice (const :tag "None" nil)
391                  (const :tag "Use `.signature' file" t)
392                  (string :tag "String to insert")
393                  (sexp :tag "Expression to evaluate"))
394   :group 'sendmail)
395 (put 'mail-signature 'risky-local-variable t)
396
397 ;;;###autoload
398 (defcustom mail-signature-file "~/.signature"
399   "File containing the text inserted at end of mail buffer."
400   :type 'file
401   :group 'sendmail)
402
403 ;;;###autoload
404 (defcustom mail-default-directory "~/"
405   "Directory for mail buffers.
406 Value of `default-directory' for mail buffers.
407 This directory is used for auto-save files of mail buffers."
408   :type '(directory :tag "Directory")
409   :group 'sendmail
410   :version "22.1")
411
412 (defvar mail-reply-action nil)
413 (defvar mail-send-actions nil
414   "A list of actions to be performed upon successful sending of a message.")
415 (put 'mail-reply-action 'permanent-local t)
416 (put 'mail-send-actions 'permanent-local t)
417
418 ;;;###autoload
419 (defcustom mail-default-headers nil
420   "A string containing header lines, to be inserted in outgoing messages.
421 It is inserted before you edit the message,
422 so you can edit or delete these lines."
423   :type '(choice (const nil) string)
424   :group 'sendmail)
425
426 ;;;###autoload
427 (defcustom mail-bury-selects-summary t
428   "If non-nil, try to show RMAIL summary buffer after returning from mail.
429 The functions \\[mail-send-on-exit] or \\[mail-dont-send] select
430 the RMAIL summary buffer before returning, if it exists and this variable
431 is non-nil."
432   :type 'boolean
433   :group 'sendmail)
434
435 ;;;###autoload
436 (defcustom mail-send-nonascii 'mime
437   "Specify whether to allow sending non-ASCII characters in mail.
438 If t, that means do allow it.  nil means don't allow it.
439 `query' means ask the user each time.
440 `mime' means add an appropriate MIME header if none already present.
441 The default is `mime'.
442 Including non-ASCII characters in a mail message can be problematical
443 for the recipient, who may not know how to decode them properly."
444   :type '(choice (const t) (const nil) (const query) (const mime))
445   :group 'sendmail)
446
447 (defcustom mail-use-dsn nil
448   "Ask MTA for notification of failed, delayed or successful delivery.
449 Note that only some MTAs (currently only recent versions of Sendmail)
450 support Delivery Status Notification."
451   :group 'sendmail
452   :type '(repeat (radio (const :tag "Failure" failure)
453                         (const :tag "Delay" delay)
454                         (const :tag "Success" success)))
455   :version "22.1")
456
457 ;; Note: could use /usr/ucb/mail instead of sendmail;
458 ;; options -t, and -v if not interactive.
459 (defvar mail-mailer-swallows-blank-line
460   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)" system-configuration)
461            (file-readable-p "/etc/sendmail.cf")
462            (with-temp-buffer
463              (insert-file-contents "/etc/sendmail.cf")
464              (goto-char (point-min))
465              (let ((case-fold-search nil))
466                (re-search-forward "^OR\\>" nil t))))
467       ;; According to RFC822, "The field-name must be composed of printable
468       ;; ASCII characters (i.e. characters that have decimal values between
469       ;; 33 and 126, except colon)", i.e. any chars except ctl chars,
470       ;; space, or colon.
471       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
472   "Set this non-nil if the system's mailer runs the header and body together.
473 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
474 The value should be an expression to test whether the problem will
475 actually occur.")
476
477 (defvar mail-mode-syntax-table
478   (let ((st (make-syntax-table)))
479     ;; define-derived-mode will make it inherit from text-mode-syntax-table.
480     (modify-syntax-entry ?% ". " st)
481     st)
482   "Syntax table used while in `mail-mode'.")
483
484 (defvar mail-font-lock-keywords
485   (eval-when-compile
486     (let* ((cite-chars "[>|}]")
487            (cite-prefix "[:alpha:]")
488            (cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
489       (list '("^\\(To\\|Newsgroups\\):" . font-lock-function-name-face)
490             '("^\\(B?CC\\|Reply-to\\|Mail-\\(reply\\|followup\\)-to\\):" . font-lock-keyword-face)
491             '("^\\(Subject:\\)[ \t]*\\(.+\\)?"
492               (1 font-lock-comment-face)
493 ;;            (2 font-lock-type-face nil t)
494               )
495             ;; Use EVAL to delay in case `mail-header-separator' gets changed.
496             '(eval .
497               (let ((separator (if (zerop (length mail-header-separator))
498                                    " \\`\\' "
499                                  (regexp-quote mail-header-separator))))
500                 (cons (concat "^" separator "$") 'font-lock-warning-face)))
501             ;; Use MATCH-ANCHORED to effectively anchor the regexp left side.
502             `(,cite-chars
503               (,(concat "\\=[ \t]*"
504                         "\\(\\(\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
505                         "\\(" cite-chars "[ \t]*\\)\\)+\\)"
506                         "\\(.*\\)")
507                (beginning-of-line) (end-of-line)
508                (1 font-lock-comment-delimiter-face nil t)
509                (5 font-lock-comment-face nil t)))
510             '("^\\(X-[A-Za-z0-9-]+\\|In-reply-to\\):.*\\(\n[ \t]+.*\\)*$"
511               . font-lock-string-face))))
512   "Additional expressions to highlight in Mail mode.")
513
514 \f
515 (defun sendmail-sync-aliases ()
516   (when mail-personal-alias-file
517     (let ((modtime (nth 5 (file-attributes mail-personal-alias-file))))
518       (or (equal mail-alias-modtime modtime)
519           (setq mail-alias-modtime modtime
520                 mail-aliases t)))))
521
522 (defun mail-setup (to subject in-reply-to cc replybuffer actions)
523   (or mail-default-reply-to
524       (setq mail-default-reply-to (getenv "REPLYTO")))
525   (sendmail-sync-aliases)
526   (if (eq mail-aliases t)
527       (progn
528         (setq mail-aliases nil)
529         (when mail-personal-alias-file
530           (if (file-exists-p mail-personal-alias-file)
531               (build-mail-aliases)))))
532   ;; Don't leave this around from a previous message.
533   (kill-local-variable 'buffer-file-coding-system)
534   ;; This doesn't work for enable-multibyte-characters.
535   ;; (kill-local-variable 'enable-multibyte-characters)
536   (set-buffer-multibyte default-enable-multibyte-characters)
537   (if current-input-method
538       (inactivate-input-method))
539   (setq mail-send-actions actions)
540   (setq mail-reply-action replybuffer)
541   (goto-char (point-min))
542   (if mail-setup-with-from
543       (mail-insert-from-field))
544   (insert "To: ")
545   (save-excursion
546     (if to
547         ;; Here removed code to extract names from within <...>
548         ;; on the assumption that mail-strip-quoted-names
549         ;; has been called and has done so.
550         (let ((fill-prefix "\t")
551               (address-start (point)))
552           (insert to "\n")
553           (fill-region-as-paragraph address-start (point-max))
554           (goto-char (point-max))
555           (unless (bolp)
556             (newline)))
557       (newline))
558     (if cc
559         (let ((fill-prefix "\t")
560               (address-start (progn (insert "CC: ") (point))))
561           (insert cc "\n")
562           (fill-region-as-paragraph address-start (point-max))
563           (goto-char (point-max))
564           (unless (bolp)
565             (newline))))
566     (if in-reply-to
567         (let ((fill-prefix "\t")
568               (fill-column 78)
569               (address-start (point)))
570           (insert "In-reply-to: " in-reply-to "\n")
571           (fill-region-as-paragraph address-start (point-max))
572           (goto-char (point-max))
573           (unless (bolp)
574             (newline))))
575     (insert "Subject: " (or subject "") "\n")
576     (if mail-default-headers
577         (insert mail-default-headers))
578     (if mail-default-reply-to
579         (insert "Reply-to: " mail-default-reply-to "\n"))
580     (if mail-self-blind
581         (insert "BCC: " user-mail-address "\n"))
582     (if mail-archive-file-name
583         (insert "FCC: " mail-archive-file-name "\n"))
584     (put-text-property (point)
585                        (progn
586                          (insert mail-header-separator "\n")
587                          (1- (point)))
588                        'category 'mail-header-separator)
589     ;; Insert the signature.  But remember the beginning of the message.
590     (if to (setq to (point)))
591     (cond ((eq mail-signature t)
592            (if (file-exists-p mail-signature-file)
593                (progn
594                  (insert "\n\n-- \n")
595                  (insert-file-contents mail-signature-file))))
596           ((stringp mail-signature)
597            (insert mail-signature))
598           (t
599            (eval mail-signature)))
600     (goto-char (point-max))
601     (or (bolp) (newline)))
602   (if to (goto-char to))
603   (or to subject in-reply-to
604       (set-buffer-modified-p nil))
605   (run-hooks 'mail-setup-hook))
606 \f
607 (defcustom mail-mode-hook nil
608   "Hook run by Mail mode."
609   :group 'sendmail
610   :type 'hook
611   :options '(footnote-mode))
612
613 (defvar mail-mode-abbrev-table text-mode-abbrev-table)
614 ;;;###autoload
615 (define-derived-mode mail-mode text-mode "Mail"
616   "Major mode for editing mail to be sent.
617 Like Text Mode but with these additional commands:
618
619 \\[mail-send]  mail-send (send the message)
620 \\[mail-send-and-exit]  mail-send-and-exit (send the message and exit)
621
622 Here are commands that move to a header field (and create it if there isn't):
623          \\[mail-to]  move to To:       \\[mail-subject]  move to Subj:
624          \\[mail-bcc]  move to BCC:     \\[mail-cc]  move to CC:
625          \\[mail-fcc]  move to FCC:     \\[mail-reply-to] move to Reply-To:
626          \\[mail-mail-reply-to]  move to Mail-Reply-To:
627          \\[mail-mail-followup-to] move to Mail-Followup-To:
628 \\[mail-text]  move to message text.
629 \\[mail-signature]  mail-signature (insert `mail-signature-file' file).
630 \\[mail-yank-original]  mail-yank-original (insert current message, in Rmail).
631 \\[mail-fill-yanked-message]  mail-fill-yanked-message (fill what was yanked).
632 \\[mail-sent-via]  mail-sent-via (add a sent-via field for each To or CC).
633 Turning on Mail mode runs the normal hooks `text-mode-hook' and
634 `mail-mode-hook' (in that order)."
635   (make-local-variable 'mail-reply-action)
636   (make-local-variable 'mail-send-actions)
637   (setq buffer-offer-save t)
638   (make-local-variable 'font-lock-defaults)
639   (setq font-lock-defaults '(mail-font-lock-keywords t t))
640   (make-local-variable 'paragraph-separate)
641   (make-local-variable 'normal-auto-fill-function)
642   (setq normal-auto-fill-function 'mail-mode-auto-fill)
643   (make-local-variable 'fill-paragraph-function)
644   (setq fill-paragraph-function 'mail-mode-fill-paragraph)
645   ;; Allow using comment commands to add/remove quoting (this only does
646   ;; anything if mail-yank-prefix is set to a non-nil value).
647   (set (make-local-variable 'comment-start) mail-yank-prefix)
648   (if mail-yank-prefix
649       (set (make-local-variable 'comment-start-skip)
650            (concat "^" (regexp-quote mail-yank-prefix) "[ \t]*")))
651   (make-local-variable 'adaptive-fill-regexp)
652   (setq adaptive-fill-regexp
653         (concat "[ \t]*[-[:alnum:]]+>+[ \t]*\\|"
654                 adaptive-fill-regexp))
655   (make-local-variable 'adaptive-fill-first-line-regexp)
656   (setq adaptive-fill-first-line-regexp
657         (concat "[ \t]*[-[:alnum:]]*>+[ \t]*\\|"
658                 adaptive-fill-first-line-regexp))
659   ;; `-- ' precedes the signature.  `-----' appears at the start of the
660   ;; lines that delimit forwarded messages.
661   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
662   ;; are also sometimes used and should be separators.
663   (setq paragraph-separate (concat (regexp-quote mail-header-separator)
664                                 "$\\|\t*\\([-|#;>* ]\\|(?[0-9]+[.)]\\)+$"
665                                 "\\|[ \t]*[[:alnum:]]*>+[ \t]*$\\|[ \t]*$\\|"
666                                 "--\\( \\|-+\\)$\\|"
667                                 page-delimiter)))
668
669
670 (defun mail-header-end ()
671   "Return the buffer location of the end of headers, as a number."
672   (save-restriction
673     (widen)
674     (save-excursion
675       (rfc822-goto-eoh)
676       (point))))
677
678 (defun mail-text-start ()
679   "Return the buffer location of the start of text, as a number."
680   (save-restriction
681     (widen)
682     (save-excursion
683       (rfc822-goto-eoh)
684       (forward-line 1)
685       (point))))
686
687 (defun mail-sendmail-delimit-header ()
688   "Set up whatever header delimiter convention sendmail will use.
689 Concretely: replace the first blank line in the header with the separator."
690   (rfc822-goto-eoh)
691   (insert mail-header-separator)
692   (point))
693
694 (defun mail-sendmail-undelimit-header ()
695   "Remove header separator to put the message in correct form for sendmail.
696 Leave point at the start of the delimiter line."
697   (rfc822-goto-eoh)
698   (delete-region (point) (progn (end-of-line) (point))))
699
700 (defun mail-mode-auto-fill ()
701   "Carry out Auto Fill for Mail mode.
702 If within the headers, this makes the new lines into continuation lines."
703   (if (< (point) (mail-header-end))
704       (let ((old-line-start (save-excursion (beginning-of-line) (point))))
705         (if (do-auto-fill)
706             (save-excursion
707               (beginning-of-line)
708               (while (not (eq (point) old-line-start))
709                 ;; Use insert-before-markers in case we're inserting
710                 ;; before the saved value of point (which is common).
711                 (insert-before-markers "   ")
712                 (forward-line -1))
713               t)))
714     (do-auto-fill)))
715
716 (defun mail-mode-fill-paragraph (arg)
717   ;; Do something special only if within the headers.
718   (if (< (point) (mail-header-end))
719       (let (beg end fieldname)
720         (when (prog1 (re-search-backward "^[-a-zA-Z]+:" nil 'yes)
721                 (setq beg (point)))
722         (setq fieldname
723                 (downcase (buffer-substring beg (1- (match-end 0))))))
724         (forward-line 1)
725         ;; Find continuation lines and get rid of their continuation markers.
726         (while (looking-at "[ \t]")
727           (delete-horizontal-space)
728           (forward-line 1))
729         (setq end (point-marker))
730         (goto-char beg)
731         ;; If this field contains addresses,
732         ;; make sure we can fill after each address.
733         (if (member fieldname
734                     '("to" "cc" "bcc" "from" "reply-to"
735                       "mail-reply-to" "mail-followup-to"
736                       "resent-to" "resent-cc" "resent-bcc"
737                       "resent-from" "resent-reply-to"))
738             (while (search-forward "," end t)
739               (or (looking-at "[ \t]")
740                   (insert " "))))
741         (fill-region-as-paragraph beg end arg)
742         ;; Mark all lines except the first as continuations.
743         (goto-char beg)
744         (forward-line 1)
745         (while (< (point) end)
746           (insert "  ")
747           (forward-line 1))
748         (move-marker end nil)
749         t)))
750 \f
751 ;; User-level commands for sending.
752
753 (defun mail-send-and-exit (&optional arg)
754   "Send message like `mail-send', then, if no errors, exit from mail buffer.
755 Prefix arg means don't delete this window."
756   (interactive "P")
757   (mail-send)
758   (mail-bury arg))
759
760 (defun mail-dont-send (&optional arg)
761   "Don't send the message you have been editing.
762 Prefix arg means don't delete this window."
763   (interactive "P")
764   (mail-bury arg))
765
766 (defun mail-bury (&optional arg)
767   "Bury this mail buffer."
768   (let ((newbuf (other-buffer (current-buffer))))
769     (bury-buffer (current-buffer))
770     (if (and (or (window-dedicated-p (frame-selected-window))
771                  (cdr (assq 'mail-dedicated-frame (frame-parameters))))
772              (not (null (delq (selected-frame) (visible-frame-list)))))
773         (progn
774           (if (display-multi-frame-p)
775               (delete-frame (selected-frame))
776             ;; The previous frame is where normally they have the
777             ;; RMAIL buffer displayed.
778             (other-frame -1)))
779       (let (rmail-flag summary-buffer)
780         (and (not arg)
781              (not (one-window-p))
782              (with-current-buffer
783                  (window-buffer (next-window (selected-window) 'not))
784                (setq rmail-flag (eq major-mode 'rmail-mode))
785                (setq summary-buffer
786                      (and mail-bury-selects-summary
787                           (boundp 'rmail-summary-buffer)
788                           rmail-summary-buffer
789                           (buffer-name rmail-summary-buffer)
790                           (not (get-buffer-window rmail-summary-buffer))
791                           rmail-summary-buffer))))
792         (if rmail-flag
793             ;; If the Rmail buffer has a summary, show that.
794             (if summary-buffer (switch-to-buffer summary-buffer)
795               (delete-window))
796           (switch-to-buffer newbuf))))))
797
798 (defcustom mail-send-hook nil
799   "Hook run just before sending mail with `mail-send'."
800   :type 'hook
801   :options '(flyspell-mode-off)
802   :group 'sendmail)
803
804 ;;;###autoload
805 (defcustom mail-mailing-lists nil "\
806 *List of mailing list addresses the user is subscribed to.
807
808 The variable is used to trigger insertion of the \"Mail-Followup-To\"
809 header when sending a message to a mailing list."
810   :type '(repeat string)
811   :group 'sendmail)
812
813
814 (defun mail-send ()
815   "Send the message in the current buffer.
816 If `mail-interactive' is non-nil, wait for success indication
817 or error messages, and inform user.
818 Otherwise any failure is reported in a message back to
819 the user from the mailer."
820   (interactive)
821   (if (if buffer-file-name
822           (y-or-n-p "Send buffer contents as mail message? ")
823         (or (buffer-modified-p)
824             (y-or-n-p "Message already sent; resend? ")))
825       (let ((inhibit-read-only t)
826             (opoint (point))
827             (ml (when mail-mailing-lists
828                 ;; The surrounding regexp assumes the use of
829                 ;; `mail-strip-quoted-names' on addresses before matching
830                 ;; Cannot deal with full RFC 822 freedom, but that is
831                 ;; unlikely to be problematic.
832                 (concat "\\(?:[[:space:];,]\\|\\`\\)"
833                         (regexp-opt mail-mailing-lists t)
834                         "\\(?:[[:space:];,]\\|\\'\\)"))))
835         ;; If there are mailing lists defined
836         (when ml
837           (save-excursion
838             (let* ((to (mail-fetch-field "to" nil t))
839                    (cc (mail-fetch-field "cc" nil t))
840                    (new-header-values   ; To: and Cc:
841                     (mail-strip-quoted-names
842                      (concat to (when cc (concat ", " cc))))))
843               ;; If message goes to known mailing list ...
844               (when (string-match ml new-header-values)
845                 ;; Add Mail-Followup-To if none yet
846                 (unless (mail-fetch-field "mail-followup-to")
847                   (goto-char (mail-header-end))
848                   (insert "Mail-Followup-To: "
849                           (let ((l))
850                             (mapc
851                              ;; remove duplicates
852                              '(lambda (e)
853                                 (unless (member e l)
854                                   (push e l)))
855                              (split-string new-header-values
856                                            ",[[:space:]]+" t))
857                             (mapconcat 'identity l ", "))
858                           "\n"))
859                 ;; Add Mail-Reply-To if none yet
860                 (unless (mail-fetch-field "mail-reply-to")
861                   (goto-char (mail-header-end))
862                   (insert "Mail-Reply-To: "
863                           (or (mail-fetch-field "reply-to")
864                               user-mail-address)
865                           "\n"))))))
866         (unless (memq mail-send-nonascii '(t mime))
867           (goto-char (point-min))
868           (skip-chars-forward "\0-\177")
869           (or (= (point) (point-max))
870               (if (eq mail-send-nonascii 'query)
871                   (or (y-or-n-p "Message contains non-ASCII characters; send anyway? ")
872                       (error "Aborted"))
873                 (error "Message contains non-ASCII characters"))))
874         ;; Complain about any invalid line.
875         (goto-char (point-min))
876         (re-search-forward (regexp-quote mail-header-separator) (point-max) t)
877         (let ((header-end (or (match-beginning 0) (point-max))))
878           (goto-char (point-min))
879           (while (< (point) header-end)
880             (unless (looking-at "[ \t]\\|.*:\\|$")
881               (push-mark opoint)
882               (error "Invalid header line (maybe a continuation line lacks initial whitespace)"))
883             (forward-line 1)))
884         (goto-char opoint)
885         (run-hooks 'mail-send-hook)
886         (message "Sending...")
887         (funcall send-mail-function)
888         ;; Now perform actions on successful sending.
889         (while mail-send-actions
890           (condition-case nil
891               (apply (car (car mail-send-actions))
892                      (cdr (car mail-send-actions)))
893             (error))
894           (setq mail-send-actions (cdr mail-send-actions)))
895         (message "Sending...done")
896         ;; If buffer has no file, mark it as unmodified and delete auto-save.
897         (if (not buffer-file-name)
898             (progn
899               (set-buffer-modified-p nil)
900               (delete-auto-save-file-if-necessary t))))))
901
902 (defun mail-envelope-from ()
903   "Return the envelope mail address to use when sending mail.
904 This function uses `mail-envelope-from'."
905   (if (eq mail-envelope-from 'header)
906       (nth 1 (mail-extract-address-components
907               (mail-fetch-field "From")))
908     mail-envelope-from))
909 \f
910 ;; This does the real work of sending a message via sendmail.
911 ;; It is called via the variable send-mail-function.
912
913 ;;;###autoload
914 (defvar sendmail-coding-system nil
915   "*Coding system for encoding the outgoing mail.
916 This has higher priority than `default-buffer-file-coding-system'
917 and `default-sendmail-coding-system',
918 but lower priority than the local value of `buffer-file-coding-system'.
919 See also the function `select-message-coding-system'.")
920
921 ;;;###autoload
922 (defvar default-sendmail-coding-system 'iso-latin-1
923   "Default coding system for encoding the outgoing mail.
924 This variable is used only when `sendmail-coding-system' is nil.
925
926 This variable is set/changed by the command `set-language-environment'.
927 User should not set this variable manually,
928 instead use `sendmail-coding-system' to get a constant encoding
929 of outgoing mails regardless of the current language environment.
930 See also the function `select-message-coding-system'.")
931
932 (defun mail-insert-from-field ()
933   (let* ((login user-mail-address)
934          (fullname (user-full-name))
935          (quote-fullname nil))
936     (if (string-match "[^\0-\177]" fullname)
937         (setq fullname (rfc2047-encode-string fullname)
938               quote-fullname t))
939     (cond ((eq mail-from-style 'angles)
940            (insert "From: " fullname)
941            (let ((fullname-start (+ (point-min) 6))
942                  (fullname-end (point-marker)))
943              (goto-char fullname-start)
944              ;; Look for a character that cannot appear unquoted
945              ;; according to RFC 822.
946              (if (or (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
947                                         fullname-end 1)
948                      quote-fullname)
949                  (progn
950                    ;; Quote fullname, escaping specials.
951                    (goto-char fullname-start)
952                    (insert "\"")
953                    (while (re-search-forward "[\"\\]"
954                                              fullname-end 1)
955                      (replace-match "\\\\\\&" t))
956                    (insert "\""))))
957            (insert " <" login ">\n"))
958           ((eq mail-from-style 'parens)
959            (insert "From: " login " (")
960            (let ((fullname-start (point)))
961              (if quote-fullname
962                  (insert "\""))
963              (insert fullname)
964              (if quote-fullname
965                  (insert "\""))
966              (let ((fullname-end (point-marker)))
967                (goto-char fullname-start)
968                ;; RFC 822 says \ and nonmatching parentheses
969                ;; must be escaped in comments.
970                ;; Escape every instance of ()\ ...
971                (while (re-search-forward "[()\\]" fullname-end 1)
972                  (replace-match "\\\\\\&" t))
973                ;; ... then undo escaping of matching parentheses,
974                ;; including matching nested parentheses.
975                (goto-char fullname-start)
976                (while (re-search-forward
977                        "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
978                        fullname-end 1)
979                  (replace-match "\\1(\\3)" t)
980                  (goto-char fullname-start))))
981            (insert ")\n"))
982           ((null mail-from-style)
983            (insert "From: " login "\n"))
984           ((eq mail-from-style 'system-default)
985            nil)
986           (t (error "Invalid value for `mail-from-style'")))))
987
988 (defun sendmail-send-it ()
989   "Send the current mail buffer using the Sendmail package.
990 This is a suitable value for `send-mail-function'.  It sends using the
991 external program defined by `sendmail-program'."
992   (require 'mail-utils)
993   (let ((errbuf (if mail-interactive
994                     (generate-new-buffer " sendmail errors")
995                   0))
996         (tembuf (generate-new-buffer " sendmail temp"))
997         (multibyte enable-multibyte-characters)
998         (case-fold-search nil)
999         (selected-coding (select-message-coding-system))
1000         resend-to-addresses
1001         delimline
1002         fcc-was-found
1003         (mailbuf (current-buffer))
1004         (program (if (boundp 'sendmail-program)
1005                      sendmail-program
1006                    "/usr/lib/sendmail"))
1007         ;; Examine these variables now, so that
1008         ;; local binding in the mail buffer will take effect.
1009         (envelope-from
1010          (and mail-specify-envelope-from
1011               (or (mail-envelope-from) user-mail-address))))
1012     (unwind-protect
1013         (with-current-buffer tembuf
1014           (erase-buffer)
1015           (unless multibyte
1016             (set-buffer-multibyte nil))
1017           (insert-buffer-substring mailbuf)
1018           (goto-char (point-max))
1019           ;; require one newline at the end.
1020           (or (= (preceding-char) ?\n)
1021               (insert ?\n))
1022           ;; Change header-delimiter to be what sendmail expects.
1023           (goto-char (mail-header-end))
1024           (delete-region (point) (progn (end-of-line) (point)))
1025           (setq delimline (point-marker))
1026           (sendmail-sync-aliases)
1027           (if mail-aliases
1028               (expand-mail-aliases (point-min) delimline))
1029           (goto-char (point-min))
1030           ;; Ignore any blank lines in the header
1031           (while (and (re-search-forward "\n\n\n*" delimline t)
1032                       (< (point) delimline))
1033             (replace-match "\n"))
1034           (goto-char (point-min))
1035           ;; Look for Resent- headers.  They require sending
1036           ;; the message specially.
1037           (let ((case-fold-search t))
1038             (goto-char (point-min))
1039             (while (re-search-forward "^Resent-\\(to\\|cc\\|bcc\\):" delimline t)
1040               ;; Put a list of such addresses in resend-to-addresses.
1041               (setq resend-to-addresses
1042                     (save-restriction
1043                       (narrow-to-region (point)
1044                                         (save-excursion
1045                                           (forward-line 1)
1046                                           (while (looking-at "^[ \t]")
1047                                             (forward-line 1))
1048                                           (point)))
1049                       (append (mail-parse-comma-list)
1050                               resend-to-addresses)))
1051               ;; Delete Resent-BCC ourselves
1052               (if (save-excursion (beginning-of-line)
1053                                   (looking-at "resent-bcc"))
1054                   (delete-region (save-excursion (beginning-of-line) (point))
1055                                  (save-excursion (end-of-line) (1+ (point))))))
1056 ;;;  Apparently this causes a duplicate Sender.
1057 ;;;         ;; If the From is different than current user, insert Sender.
1058 ;;;         (goto-char (point-min))
1059 ;;;         (and (re-search-forward "^From:"  delimline t)
1060 ;;;              (progn
1061 ;;;                (require 'mail-utils)
1062 ;;;                (not (string-equal
1063 ;;;                      (mail-strip-quoted-names
1064 ;;;                       (save-restriction
1065 ;;;                         (narrow-to-region (point-min) delimline)
1066 ;;;                         (mail-fetch-field "From")))
1067 ;;;                      (user-login-name))))
1068 ;;;              (progn
1069 ;;;                (forward-line 1)
1070 ;;;                (insert "Sender: " (user-login-name) "\n")))
1071             ;; Don't send out a blank subject line
1072             (goto-char (point-min))
1073             (if (re-search-forward "^Subject:\\([ \t]*\n\\)+\\b" delimline t)
1074                 (replace-match "")
1075               ;; This one matches a Subject just before the header delimiter.
1076               (if (and (re-search-forward "^Subject:\\([ \t]*\n\\)+" delimline t)
1077                        (= (match-end 0) delimline))
1078                   (replace-match "")))
1079             ;; Put the "From:" field in unless for some odd reason
1080             ;; they put one in themselves.
1081             (goto-char (point-min))
1082             (if (not (re-search-forward "^From:" delimline t))
1083                 (mail-insert-from-field))
1084             ;; Possibly add a MIME header for the current coding system
1085             (let (charset)
1086               (goto-char (point-min))
1087               (and (eq mail-send-nonascii 'mime)
1088                    (not (re-search-forward "^MIME-version:" delimline t))
1089                    (progn (skip-chars-forward "\0-\177")
1090                           (/= (point) (point-max)))
1091                    selected-coding
1092                    (setq charset
1093                          (coding-system-get selected-coding 'mime-charset))
1094                    (goto-char delimline)
1095                    (insert "MIME-version: 1.0\n"
1096                            "Content-type: text/plain; charset="
1097                            (symbol-name charset)
1098                            "\nContent-Transfer-Encoding: 8bit\n")))
1099             ;; Insert an extra newline if we need it to work around
1100             ;; Sun's bug that swallows newlines.
1101             (goto-char (1+ delimline))
1102             (if (eval mail-mailer-swallows-blank-line)
1103                 (newline))
1104             ;; Find and handle any FCC fields.
1105             (goto-char (point-min))
1106             (if (re-search-forward "^FCC:" delimline t)
1107                 (progn
1108                   (setq fcc-was-found t)
1109                   (mail-do-fcc delimline)))
1110             (if mail-interactive
1111                 (with-current-buffer errbuf
1112                   (erase-buffer))))
1113           (goto-char (point-min))
1114           (if (let ((case-fold-search t))
1115                 (or resend-to-addresses
1116                     (re-search-forward "^To:\\|^cc:\\|^bcc:"
1117                                        delimline t)))
1118               (let* ((default-directory "/")
1119                      (coding-system-for-write selected-coding)
1120                      (args
1121                       (append (list (point-min) (point-max)
1122                                     program
1123                                     nil errbuf nil "-oi")
1124                               (and envelope-from
1125                                    (list "-f" envelope-from))
1126 ;;;                           ;; Don't say "from root" if running under su.
1127 ;;;                           (and (equal (user-real-login-name) "root")
1128 ;;;                                (list "-f" (user-login-name)))
1129                               (and mail-alias-file
1130                                    (list (concat "-oA" mail-alias-file)))
1131                               (if mail-interactive
1132                                   ;; These mean "report errors to terminal"
1133                                   ;; and "deliver interactively"
1134                                   '("-oep" "-odi")
1135                                 ;; These mean "report errors by mail"
1136                                 ;; and "deliver in background".
1137                                 '("-oem" "-odb"))
1138                               ;; Get the addresses from the message
1139                               ;; unless this is a resend.
1140                               ;; We must not do that for a resend
1141                               ;; because we would find the original addresses.
1142                               ;; For a resend, include the specific addresses.
1143                               (or resend-to-addresses
1144                                   '("-t")
1145                                   )
1146                               (if mail-use-dsn
1147                                   (list "-N" (mapconcat 'symbol-name
1148                                                         mail-use-dsn ",")))
1149                               )
1150                       )
1151                      (exit-value (apply 'call-process-region args)))
1152                 (or (null exit-value) (eq 0 exit-value)
1153                     (error "Sending...failed with exit value %d" exit-value)))
1154             (or fcc-was-found
1155                 (error "No recipients")))
1156           (if mail-interactive
1157               (with-current-buffer errbuf
1158                 (goto-char (point-min))
1159                 (while (re-search-forward "\n\n* *" nil t)
1160                   (replace-match "; "))
1161                 (if (not (zerop (buffer-size)))
1162                     (error "Sending...failed to %s"
1163                            (buffer-substring (point-min) (point-max)))))))
1164       (kill-buffer tembuf)
1165       (if (bufferp errbuf)
1166           (kill-buffer errbuf)))))
1167
1168 (defun mail-do-fcc (header-end)
1169   (unless (markerp header-end)
1170     (error "Value of `header-end' must be a marker"))
1171   (let (fcc-list
1172         (rmailbuf (current-buffer))
1173         (time (current-time))
1174         (tembuf (generate-new-buffer " rmail output"))
1175         (case-fold-search t))
1176     (save-excursion
1177       (goto-char (point-min))
1178       (while (re-search-forward "^FCC:[ \t]*" header-end t)
1179         (push (buffer-substring (point)
1180                                 (progn
1181                                   (end-of-line)
1182                                   (skip-chars-backward " \t")
1183                                   (point)))
1184               fcc-list)
1185         (delete-region (match-beginning 0)
1186                        (progn (forward-line 1) (point))))
1187       (set-buffer tembuf)
1188       (erase-buffer)
1189       ;; This initial newline is written out if the fcc file already exists.
1190       (insert "\nFrom " (user-login-name) " "
1191               (current-time-string time) "\n")
1192       ;; Insert the time zone before the year.
1193       (forward-char -1)
1194       (forward-word -1)
1195       (require 'mail-utils)
1196       (insert (mail-rfc822-time-zone time) " ")
1197       (goto-char (point-max))
1198       (insert-buffer-substring rmailbuf)
1199       ;; Make sure messages are separated.
1200       (goto-char (point-max))
1201       (insert ?\n)
1202       (goto-char 2)
1203       ;; ``Quote'' "^From " as ">From "
1204       ;;  (note that this isn't really quoting, as there is no requirement
1205       ;;   that "^[>]+From " be quoted in the same transparent way.)
1206       (let ((case-fold-search nil))
1207         (while (search-forward "\nFrom " nil t)
1208           (forward-char -5)
1209           (insert ?>)))
1210       (dolist (fcc fcc-list)
1211         (let* ((buffer (find-buffer-visiting fcc))
1212                (curbuf (current-buffer))
1213                dont-write-the-file
1214                buffer-matches-file
1215                (beg (point-min)) (end (point-max))
1216                (beg2 (save-excursion (goto-char (point-min))
1217                                      (forward-line 2) (point))))
1218           (if buffer
1219               ;; File is present in a buffer => append to that buffer.
1220               (with-current-buffer buffer
1221                 (setq buffer-matches-file
1222                       (and (not (buffer-modified-p))
1223                            (verify-visited-file-modtime buffer)))
1224                 ;; Keep the end of the accessible portion at the same place
1225                 ;; unless it is the end of the buffer.
1226                 (let ((max (if (/= (1+ (buffer-size)) (point-max))
1227                                (point-max))))
1228                   (unwind-protect
1229                       ;; Code below lifted from rmailout.el
1230                       ;; function rmail-output-to-rmail-file:
1231                       (let ((buffer-read-only nil)
1232                             (msg (and (boundp 'rmail-current-message)
1233                                       rmail-current-message)))
1234                         ;; If MSG is non-nil, buffer is in RMAIL mode.
1235                         (if msg
1236                             (progn
1237                               ;; Append to an ordinary buffer as a
1238                               ;; Unix mail message.
1239                               (rmail-maybe-set-message-counters)
1240                               (widen)
1241                               (narrow-to-region (point-max) (point-max))
1242                               (insert "\C-l\n0, unseen,,\n*** EOOH ***\n"
1243                                       "Date: " (mail-rfc822-date) "\n")
1244                               (insert-buffer-substring curbuf beg2 end)
1245                               (insert "\n\C-_")
1246                               (goto-char (point-min))
1247                               (widen)
1248                               (search-backward "\n\^_")
1249                               (narrow-to-region (point) (point-max))
1250                               (rmail-count-new-messages t)
1251                               (rmail-show-message msg)
1252                               (setq max nil))
1253                           ;; Output file not in rmail mode
1254                           ;; => just insert at the end.
1255                           (narrow-to-region (point-min) (1+ (buffer-size)))
1256                           (goto-char (point-max))
1257                           (insert-buffer-substring curbuf beg end))
1258                         (or buffer-matches-file
1259                             (progn
1260                               (if (y-or-n-p (format "Save file %s? "
1261                                                     fcc))
1262                                   (save-buffer))
1263                               (setq dont-write-the-file t))))
1264                     (if max (narrow-to-region (point-min) max))))))
1265           ;; Append to the file directly,
1266           ;; unless we've already taken care of it.
1267           (unless dont-write-the-file
1268             (if (and (file-exists-p fcc)
1269                      ;; Check that the file isn't empty.  We don't
1270                      ;; want to insert a newline at the start of an
1271                      ;; empty file.
1272                      (not (zerop (nth 7 (file-attributes fcc))))
1273                      (mail-file-babyl-p fcc))
1274                 ;; If the file is a Babyl file,
1275                 ;; convert the message to Babyl format.
1276                 (let ((coding-system-for-write
1277                        (or rmail-file-coding-system
1278                            'emacs-mule)))
1279                   (with-current-buffer (get-buffer-create " mail-temp")
1280                     (setq buffer-read-only nil)
1281                     (erase-buffer)
1282                     (insert "\C-l\n0, unseen,,\n*** EOOH ***\nDate: "
1283                             (mail-rfc822-date) "\n")
1284                     (insert-buffer-substring curbuf beg2 end)
1285                     (insert "\n\C-_")
1286                     (write-region (point-min) (point-max) fcc t)
1287                     (erase-buffer)))
1288               (write-region
1289                (1+ (point-min)) (point-max) fcc t)))
1290           (and buffer (not dont-write-the-file)
1291                (with-current-buffer buffer
1292                  (set-visited-file-modtime))))))
1293     (kill-buffer tembuf)))
1294
1295 (defun mail-sent-via ()
1296   "Make a Sent-via header line from each To or CC header line."
1297   (interactive)
1298   (save-excursion
1299     ;; put a marker at the end of the header
1300     (let ((end (copy-marker (mail-header-end)))
1301           (case-fold-search t))
1302       (goto-char (point-min))
1303       ;; search for the To: lines and make Sent-via: lines from them
1304       ;; search for the next To: line
1305       (while (re-search-forward "^\\(to\\|cc\\):" end t)
1306         ;; Grab this line plus all its continuations, sans the `to:'.
1307         (let ((to-line
1308                (buffer-substring (point)
1309                                  (progn
1310                                    (if (re-search-forward "^[^ \t\n]" end t)
1311                                        (backward-char 1)
1312                                      (goto-char end))
1313                                    (point)))))
1314           ;; Insert a copy, with altered header field name.
1315           (insert-before-markers "Sent-via:" to-line))))))
1316 \f
1317 (defun mail-to ()
1318   "Move point to end of To-field."
1319   (interactive)
1320   (expand-abbrev)
1321   (mail-position-on-field "To"))
1322
1323 (defun mail-subject ()
1324   "Move point to end of Subject-field."
1325   (interactive)
1326   (expand-abbrev)
1327   (mail-position-on-field "Subject"))
1328
1329 (defun mail-cc ()
1330   "Move point to end of CC-field.  Create a CC field if none."
1331   (interactive)
1332   (expand-abbrev)
1333   (or (mail-position-on-field "cc" t)
1334       (progn (mail-position-on-field "to")
1335              (insert "\nCC: "))))
1336
1337 (defun mail-bcc ()
1338   "Move point to end of BCC-field.  Create a BCC field if none."
1339   (interactive)
1340   (expand-abbrev)
1341   (or (mail-position-on-field "bcc" t)
1342       (progn (mail-position-on-field "to")
1343              (insert "\nBCC: "))))
1344
1345 (defun mail-fcc (folder)
1346   "Add a new FCC field, with file name completion."
1347   (interactive "FFolder carbon copy: ")
1348   (expand-abbrev)
1349   (or (mail-position-on-field "fcc" t)  ;Put new field after exiting FCC.
1350       (mail-position-on-field "to"))
1351   (insert "\nFCC: " folder))
1352
1353 (defun mail-reply-to ()
1354   "Move point to end of Reply-To-field.  Create a Reply-To field if none."
1355   (interactive)
1356   (expand-abbrev)
1357   (mail-position-on-field "Reply-To"))
1358
1359 (defun mail-mail-reply-to ()
1360   "Move point to end of Mail-Reply-To field.
1361 Create a Mail-Reply-To field if none."
1362   (interactive)
1363   (expand-abbrev)
1364   (or (mail-position-on-field "mail-reply-to" t)
1365       (progn (mail-position-on-field "to")
1366            (insert "\nMail-Reply-To: "))))
1367
1368 (defun mail-mail-followup-to ()
1369   "Move point to end of Mail-Followup-To field.
1370 Create a Mail-Followup-To field if none."
1371   (interactive)
1372   (expand-abbrev)
1373   (or (mail-position-on-field "mail-followup-to" t)
1374       (progn (mail-position-on-field "to")
1375            (insert "\nMail-Followup-To: "))))
1376
1377 (defun mail-position-on-field (field &optional soft)
1378   (let (end
1379         (case-fold-search t))
1380     (setq end (mail-header-end))
1381     (goto-char (point-min))
1382     (if (re-search-forward (concat "^" (regexp-quote field) ":") end t)
1383         (progn
1384           (re-search-forward "^[^ \t]" nil 'move)
1385           (beginning-of-line)
1386           (skip-chars-backward "\n")
1387           t)
1388       (or soft
1389           (progn (goto-char end)
1390                  (insert field ": \n")
1391                  (skip-chars-backward "\n")))
1392       nil)))
1393
1394 (defun mail-text ()
1395   "Move point to beginning of text field."
1396   (interactive)
1397   (expand-abbrev)
1398   (goto-char (mail-text-start)))
1399 \f
1400 (defun mail-signature (&optional atpoint)
1401   "Sign letter with signature based on `mail-signature-file'.
1402 Prefix arg means put contents at point."
1403   (interactive "P")
1404   (save-excursion
1405     (or atpoint
1406         (goto-char (point-max)))
1407     (skip-chars-backward " \t\n")
1408     (end-of-line)
1409     (or atpoint
1410         (delete-region (point) (point-max)))
1411     (if (stringp mail-signature)
1412         (insert mail-signature)
1413       (insert "\n\n-- \n")
1414       (insert-file-contents (expand-file-name mail-signature-file)))))
1415
1416 (defun mail-fill-yanked-message (&optional justifyp)
1417   "Fill the paragraphs of a message yanked into this one.
1418 Numeric argument means justify as well."
1419   (interactive "P")
1420   (save-excursion
1421     (goto-char (mail-text-start))
1422     (fill-individual-paragraphs (point)
1423                                 (point-max)
1424                                 justifyp
1425                                 mail-citation-prefix-regexp)))
1426
1427 (defun mail-indent-citation ()
1428   "Modify text just inserted from a message to be cited.
1429 The inserted text should be the region.
1430 When this function returns, the region is again around the modified text.
1431
1432 Normally, indent each nonblank line `mail-indentation-spaces' spaces.
1433 However, if `mail-yank-prefix' is non-nil, insert that prefix on each line."
1434   (mail-yank-clear-headers (region-beginning) (region-end))
1435   (if (null mail-yank-prefix)
1436       (indent-rigidly (region-beginning) (region-end)
1437                       mail-indentation-spaces)
1438     (save-excursion
1439       (let ((end (set-marker (make-marker) (region-end))))
1440         (goto-char (region-beginning))
1441         (while (< (point) end)
1442           (insert mail-yank-prefix)
1443           (forward-line 1))))))
1444
1445 (defun mail-yank-original (arg)
1446   "Insert the message being replied to, if any (in rmail).
1447 Puts point after the text and mark before.
1448 Normally, indents each nonblank line ARG spaces (default 3).
1449 However, if `mail-yank-prefix' is non-nil, insert that prefix on each line.
1450
1451 Just \\[universal-argument] as argument means don't indent, insert no prefix,
1452 and don't delete any header fields."
1453   (interactive "P")
1454   (if mail-reply-action
1455       (let ((start (point))
1456             (original mail-reply-action))
1457         (and (consp original) (eq (car original) 'insert-buffer)
1458              (setq original (nth 1 original)))
1459         (if (consp original)
1460             (apply (car original) (cdr original))
1461           ;; If the original message is in another window in the same frame,
1462           ;; delete that window to save screen space.
1463           ;; t means don't alter other frames.
1464           (delete-windows-on original t)
1465           (with-no-warnings
1466             ;; We really want this to set mark.
1467             (insert-buffer original))
1468           (set-text-properties (point) (mark t) nil))
1469         (if (consp arg)
1470             nil
1471           (goto-char start)
1472           (let ((mail-indentation-spaces (if arg (prefix-numeric-value arg)
1473                                            mail-indentation-spaces))
1474                 ;; Avoid error in Transient Mark mode
1475                 ;; on account of mark's being inactive.
1476                 (mark-even-if-inactive t))
1477             (cond (mail-citation-hook
1478                    ;; Bind mail-citation-header to the inserted
1479                    ;; message's header.
1480                    (let ((mail-citation-header
1481                           (buffer-substring-no-properties
1482                            start
1483                            (save-excursion
1484                              (save-restriction
1485                                (narrow-to-region start (point-max))
1486                                (goto-char start)
1487                                (rfc822-goto-eoh)
1488                                (point))))))
1489                      (run-hooks 'mail-citation-hook)))
1490                   (mail-yank-hooks
1491                    (run-hooks 'mail-yank-hooks))
1492                   (t
1493                    (mail-indent-citation)))))
1494         ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1495         ;; It is cleaner to avoid activation, even though the command
1496         ;; loop would deactivate the mark because we inserted text.
1497         (goto-char (prog1 (mark t)
1498                      (set-marker (mark-marker) (point) (current-buffer))))
1499         (if (not (eolp)) (insert ?\n)))))
1500
1501 (defun mail-yank-clear-headers (start end)
1502   (if (< end start)
1503       (let (temp)
1504         (setq temp start start end end temp)))
1505   (if mail-yank-ignored-headers
1506       (save-excursion
1507         (goto-char start)
1508         (if (search-forward "\n\n" end t)
1509             (save-restriction
1510               (narrow-to-region start (point))
1511               (goto-char start)
1512               (while (let ((case-fold-search t))
1513                        (re-search-forward mail-yank-ignored-headers nil t))
1514                 (beginning-of-line)
1515                 (delete-region (point)
1516                                (progn (re-search-forward "\n[^ \t]")
1517                                       (forward-char -1)
1518                                       (point)))))))))
1519
1520 (defun mail-yank-region (arg)
1521   "Insert the selected region from the message being replied to.
1522 Puts point after the text and mark before.
1523 Normally, indents each nonblank line ARG spaces (default 3).
1524 However, if `mail-yank-prefix' is non-nil, insert that prefix on each line.
1525
1526 Just \\[universal-argument] as argument means don't indent, insert no prefix,
1527 and don't delete any header fields."
1528   (interactive "P")
1529   (and (consp mail-reply-action)
1530        (eq (car mail-reply-action) 'insert-buffer)
1531        (with-current-buffer (nth 1 mail-reply-action)
1532          (or (mark t)
1533              (error "No mark set: %S" (current-buffer))))
1534        (let ((buffer (nth 1 mail-reply-action))
1535              (start (point))
1536              ;; Avoid error in Transient Mark mode
1537              ;; on account of mark's being inactive.
1538              (mark-even-if-inactive t))
1539          ;; Insert the citation text.
1540          (insert (with-current-buffer buffer
1541                    (buffer-substring-no-properties (point) (mark))))
1542          (push-mark start)
1543          ;; Indent or otherwise annotate the citation text.
1544          (if (consp arg)
1545              nil
1546            (let ((mail-indentation-spaces (if arg (prefix-numeric-value arg)
1547                                             mail-indentation-spaces)))
1548              (if mail-citation-hook
1549                  ;; Bind mail-citation-hook to the original message's header.
1550                  (let ((mail-citation-header
1551                         (with-current-buffer buffer
1552                           (buffer-substring-no-properties
1553                            (point-min)
1554                            (save-excursion
1555                              (goto-char (point-min))
1556                              (rfc822-goto-eoh)
1557                              (point))))))
1558                    (run-hooks 'mail-citation-hook))
1559                (if mail-yank-hooks
1560                    (run-hooks 'mail-yank-hooks)
1561                  (mail-indent-citation))))))))
1562
1563 (defun mail-split-line ()
1564   "Split current line, moving portion beyond point vertically down.
1565 If the current line has `mail-yank-prefix', insert it on the new line."
1566   (interactive "*")
1567   (split-line mail-yank-prefix))
1568
1569 \f
1570 (defun mail-attach-file (&optional file)
1571   "Insert a file at the end of the buffer, with separator lines around it."
1572   (interactive "fAttach file: ")
1573   (save-excursion
1574     (goto-char (point-max))
1575     (or (bolp) (newline))
1576     (newline)
1577     (let ((start (point))
1578           middle)
1579       (insert (format "===File %s===" file))
1580       (insert-char ?= (max 0 (- 60 (current-column))))
1581       (newline)
1582       (setq middle (point))
1583       (insert "============================================================\n")
1584       (push-mark)
1585       (goto-char middle)
1586       (insert-file-contents file)
1587       (or (bolp) (newline))
1588       (goto-char start))))
1589 \f
1590 ;; Put these commands last, to reduce chance of lossage from quitting
1591 ;; in middle of loading the file.
1592
1593 ;;;###autoload (add-hook 'same-window-buffer-names "*mail*")
1594
1595 ;;;###autoload
1596 (defun mail (&optional noerase to subject in-reply-to cc replybuffer actions)
1597   "Edit a message to be sent.  Prefix arg means resume editing (don't erase).
1598 When this function returns, the buffer `*mail*' is selected.
1599 The value is t if the message was newly initialized; otherwise, nil.
1600
1601 Optionally, the signature file `mail-signature-file' can be inserted at the
1602 end; see the variable `mail-signature'.
1603
1604 \\<mail-mode-map>
1605 While editing message, type \\[mail-send-and-exit] to send the message and exit.
1606
1607 Various special commands starting with C-c are available in sendmail mode
1608 to move to message header fields:
1609 \\{mail-mode-map}
1610
1611 If `mail-self-blind' is non-nil, a BCC to yourself is inserted
1612 when the message is initialized.
1613
1614 If `mail-default-reply-to' is non-nil, it should be an address (a string);
1615 a Reply-to: field with that address is inserted.
1616
1617 If `mail-archive-file-name' is non-nil, an FCC field with that file name
1618 is inserted.
1619
1620 The normal hook `mail-setup-hook' is run after the message is
1621 initialized.  It can add more default fields to the message.
1622
1623 The first argument, NOERASE, determines what to do when there is
1624 an existing modified `*mail*' buffer.  If NOERASE is nil, the
1625 existing mail buffer is used, and the user is prompted whether to
1626 keep the old contents or to erase them.  If NOERASE has the value
1627 `new', a new mail buffer will be created instead of using the old
1628 one.  Any other non-nil value means to always select the old
1629 buffer without erasing the contents.
1630
1631 The second through fifth arguments,
1632  TO, SUBJECT, IN-REPLY-TO and CC, specify if non-nil
1633  the initial contents of those header fields.
1634  These arguments should not have final newlines.
1635 The sixth argument REPLYBUFFER is a buffer which contains an
1636  original message being replied to, or else an action
1637  of the form (FUNCTION . ARGS) which says how to insert the original.
1638  Or it can be nil, if not replying to anything.
1639 The seventh argument ACTIONS is a list of actions to take
1640  if/when the message is sent.  Each action looks like (FUNCTION . ARGS);
1641  when the message is sent, we apply FUNCTION to ARGS.
1642  This is how Rmail arranges to mark messages `answered'."
1643   (interactive "P")
1644 ;;;  This is commented out because I found it was confusing in practice.
1645 ;;;  It is easy enough to rename *mail* by hand with rename-buffer
1646 ;;;  if you want to have multiple mail buffers.
1647 ;;;  And then you can control which messages to save. --rms.
1648 ;;;  (let ((index 1)
1649 ;;;     buffer)
1650 ;;;    ;; If requested, look for a mail buffer that is modified and go to it.
1651 ;;;    (if noerase
1652 ;;;     (progn
1653 ;;;       (while (and (setq buffer
1654 ;;;                         (get-buffer (if (= 1 index) "*mail*"
1655 ;;;                                       (format "*mail*<%d>" index))))
1656 ;;;                   (not (buffer-modified-p buffer)))
1657 ;;;         (setq index (1+ index)))
1658 ;;;       (if buffer (switch-to-buffer buffer)
1659 ;;;         ;; If none exists, start a new message.
1660 ;;;         ;; This will never re-use an existing unmodified mail buffer
1661 ;;;         ;; (since index is not 1 anymore).  Perhaps it should.
1662 ;;;         (setq noerase nil))))
1663 ;;;    ;; Unless we found a modified message and are happy, start a new message.
1664 ;;;    (if (not noerase)
1665 ;;;     (progn
1666 ;;;       ;; Look for existing unmodified mail buffer.
1667 ;;;       (while (and (setq buffer
1668 ;;;                         (get-buffer (if (= 1 index) "*mail*"
1669 ;;;                                       (format "*mail*<%d>" index))))
1670 ;;;                   (buffer-modified-p buffer))
1671 ;;;         (setq index (1+ index)))
1672 ;;;       ;; If none, make a new one.
1673 ;;;       (or buffer
1674 ;;;           (setq buffer (generate-new-buffer "*mail*")))
1675 ;;;       ;; Go there and initialize it.
1676 ;;;       (switch-to-buffer buffer)
1677 ;;;       (erase-buffer)
1678 ;;;          (setq default-directory (expand-file-name "~/"))
1679 ;;;          (auto-save-mode auto-save-default)
1680 ;;;          (mail-mode)
1681 ;;;          (mail-setup to subject in-reply-to cc replybuffer actions)
1682 ;;;       (if (and buffer-auto-save-file-name
1683 ;;;                (file-exists-p buffer-auto-save-file-name))
1684 ;;;           (message "Auto save file for draft message exists; consider M-x mail-recover"))
1685 ;;;          t))
1686
1687   (if (eq noerase 'new)
1688       (pop-to-buffer (generate-new-buffer "*mail*"))
1689     (and noerase
1690          (not (get-buffer "*mail*"))
1691          (setq noerase nil))
1692     (pop-to-buffer "*mail*"))
1693
1694   ;; Avoid danger that the auto-save file can't be written.
1695   (let ((dir (expand-file-name
1696               (file-name-as-directory mail-default-directory))))
1697     (if (file-exists-p dir)
1698         (setq default-directory dir)))
1699   ;; Only call auto-save-mode if necessary, to avoid changing auto-save file.
1700   (if (or (and auto-save-default (not buffer-auto-save-file-name))
1701           (and (not auto-save-default) buffer-auto-save-file-name))
1702       (auto-save-mode auto-save-default))
1703   (mail-mode)
1704   ;; Disconnect the buffer from its visited file
1705   ;; (in case the user has actually visited a file *mail*).
1706 ;;;  (set-visited-file-name nil)
1707   (let (initialized)
1708     (and (not (and noerase
1709                    (not (eq noerase 'new))))
1710          (if buffer-file-name
1711              (if (buffer-modified-p)
1712                  (when (y-or-n-p "Buffer has unsaved changes; reinitialize it and discard them? ")
1713                    (if (y-or-n-p "Disconnect buffer from visited file? ")
1714                        (set-visited-file-name nil))
1715                    t)
1716                (when (y-or-n-p "Reinitialize buffer, and disconnect it from the visited file? ")
1717                  (set-visited-file-name nil)
1718                  t))
1719            ;; A non-file-visiting buffer.
1720            (if (buffer-modified-p)
1721                (y-or-n-p "Unsent message being composed; erase it? ")
1722              t))
1723          (let ((inhibit-read-only t))
1724            (erase-buffer)
1725            (mail-setup to subject in-reply-to cc replybuffer actions)
1726            (setq initialized t)))
1727     (if (and buffer-auto-save-file-name
1728              (file-exists-p buffer-auto-save-file-name))
1729         (message "Auto save file for draft message exists; consider M-x mail-recover"))
1730     initialized))
1731
1732 (defun mail-recover-1 ()
1733   "Pop up a list of auto-saved draft messages so you can recover one of them."
1734   (interactive)
1735   (let ((file-name (make-auto-save-file-name))
1736         (ls-lisp-support-shell-wildcards t)
1737         non-random-len wildcard)
1738     ;; Remove the random part from the auto-save-file-name, and
1739     ;; create a wildcard which matches possible candidates.
1740     ;; Note: this knows that make-auto-save-file-name appends
1741     ;; "#<RANDOM-STUFF>#" to the buffer name, where RANDOM-STUFF
1742     ;; is the result of (make-temp-name "").
1743     (setq non-random-len
1744           (- (length file-name) (length (make-temp-name "")) 1))
1745     (setq wildcard (concat (substring file-name 0 non-random-len) "*"))
1746     (if (null (file-expand-wildcards wildcard))
1747         (message "There are no auto-saved drafts to recover")
1748       ;; Bind dired-trivial-filenames to t because all auto-save file
1749       ;; names are normally ``trivial'', so Dired will set point after
1750       ;; all the files, at buffer bottom.  We want it on the first
1751       ;; file instead.
1752       (let ((dired-trivial-filenames t))
1753         (dired-other-window wildcard (concat dired-listing-switches "t")))
1754       (rename-buffer "*Auto-saved Drafts*" t)
1755       (save-excursion
1756         (goto-char (point-min))
1757         (or (looking-at " Move to the draft file you want to recover,")
1758             (let ((inhibit-read-only t))
1759               ;; Each line starts with a space so that Font Lock mode
1760               ;; won't highlight the first character.
1761               (insert "\
1762  Move to the draft file you want to recover, then type C-c C-c
1763  to recover text of message whose composition was interrupted.
1764  To browse text of a draft, type v on the draft file's line.
1765
1766  You can also delete some of these files;
1767  type d on a line to mark that file for deletion.
1768
1769  List of possible auto-save files for recovery:
1770
1771 "))))
1772       (use-local-map
1773        (let ((map (make-sparse-keymap)))
1774          (set-keymap-parent map (current-local-map))
1775          map))
1776       (define-key (current-local-map) "v"
1777         (lambda ()
1778           (interactive)
1779           (let ((coding-system-for-read 'emacs-mule-unix))
1780             (dired-view-file))))
1781       (define-key (current-local-map) "\C-c\C-c"
1782         (lambda ()
1783           (interactive)
1784           (let ((fname (dired-get-filename))
1785                 ;; Auto-saved files are written in the internal
1786                 ;; representation, so they should be read accordingly.
1787                 (coding-system-for-read 'emacs-mule-unix))
1788             (switch-to-buffer-other-window "*mail*")
1789             (let ((buffer-read-only nil))
1790               (erase-buffer)
1791               (insert-file-contents fname nil)
1792               ;; insert-file-contents will set buffer-file-coding-system
1793               ;; to emacs-mule, which is probably not what they want to
1794               ;; use for sending the message.  But we don't know what
1795               ;; was its value before the buffer was killed or Emacs
1796               ;; crashed.  We therefore reset buffer-file-coding-system
1797               ;; to the default value, so that either the default does
1798               ;; TRT, or the user will get prompted for the right
1799               ;; encoding when they send the message.
1800               (setq buffer-file-coding-system
1801                     default-buffer-file-coding-system))))))))
1802
1803 (defun mail-recover ()
1804   "Recover interrupted mail composition from auto-save files.
1805
1806 If the mail buffer has a current valid auto-save file,
1807 the command recovers that file.  Otherwise, it displays a
1808 buffer showing the existing auto-saved draft messages;
1809 you can move to one of them and type C-c C-c to recover that one."
1810   (interactive)
1811   ;; In case they invoke us from some random buffer...
1812   (switch-to-buffer "*mail*")
1813   ;; If *mail* didn't exist, set its directory, so that auto-saved
1814   ;; drafts will be found.
1815   (let ((dir (expand-file-name
1816               (file-name-as-directory mail-default-directory))))
1817     (if (file-exists-p dir)
1818         (setq default-directory dir)))
1819   (or (eq major-mode 'mail-mode)
1820       (mail-mode))
1821   (let ((file-name buffer-auto-save-file-name))
1822     (cond ((and file-name (file-exists-p file-name))
1823            (let ((dispbuf
1824                   ;; This used to invoke `ls' via call-process, but
1825                   ;; dired-noselect is more portable to systems where
1826                   ;; `ls' is not a standard program (it will use
1827                   ;; ls-lisp instead).
1828                   (dired-noselect file-name
1829                                   (concat dired-listing-switches "t"))))
1830              (save-selected-window
1831                (select-window (display-buffer dispbuf t))
1832                (goto-char (point-min))
1833                (forward-line 2)
1834                (dired-move-to-filename)
1835                (setq dispbuf (rename-buffer "*Directory*" t)))
1836              (if (not (yes-or-no-p
1837                        (format "Recover mail draft from auto save file %s? "
1838                                file-name)))
1839                  (error "mail-recover cancelled")
1840                (let ((buffer-read-only nil)
1841                      (buffer-coding buffer-file-coding-system)
1842                      ;; Auto-save files are written in internal
1843                      ;; representation of non-ASCII characters.
1844                      (coding-system-for-read 'emacs-mule-unix))
1845                  (erase-buffer)
1846                  (insert-file-contents file-name nil)
1847                  (setq buffer-file-coding-system buffer-coding)))))
1848           (t (mail-recover-1)))))
1849
1850 ;;;###autoload
1851 (defun mail-other-window (&optional noerase to subject in-reply-to cc replybuffer sendactions)
1852   "Like `mail' command, but display mail buffer in another window."
1853   (interactive "P")
1854   (let ((pop-up-windows t)
1855         (special-display-buffer-names nil)
1856         (special-display-regexps nil)
1857         (same-window-buffer-names nil)
1858         (same-window-regexps nil))
1859     (pop-to-buffer "*mail*"))
1860   (mail noerase to subject in-reply-to cc replybuffer sendactions))
1861
1862 ;;;###autoload
1863 (defun mail-other-frame (&optional noerase to subject in-reply-to cc replybuffer sendactions)
1864   "Like `mail' command, but display mail buffer in another frame."
1865   (interactive "P")
1866   (let ((pop-up-frames t)
1867         (special-display-buffer-names nil)
1868         (special-display-regexps nil)
1869         (same-window-buffer-names nil)
1870         (same-window-regexps nil))
1871     (pop-to-buffer "*mail*"))
1872   (mail noerase to subject in-reply-to cc replybuffer sendactions))
1873
1874 ;; Do not add anything but external entries on this page.
1875
1876 (provide 'sendmail)
1877
1878 ;; arch-tag: 48bc1025-d993-4d31-8d81-2a29491f0626
1879 ;;; sendmail.el ends here