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