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