2001-01-16 Simon Josefsson <simon@josefsson.org>
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages  -*- coding: iso-latin-1 -*-
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: mail, news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This mode provides mail-sending facilities from within Emacs.  It
28 ;; consists mainly of large chunks of code from the sendmail.el,
29 ;; gnus-msg.el and rnewspost.el files.
30
31 ;;; Code:
32
33 (eval-when-compile
34   (require 'cl)
35   (defvar gnus-list-identifiers))       ; gnus-sum is required where necessary
36 (require 'mailheader)
37 (require 'nnheader)
38 ;; This is apparently necessary even though things are autoloaded:
39 (if (featurep 'xemacs)
40     (require 'mail-abbrevs))
41 (require 'mail-parse)
42 (require 'mml)
43
44 (defgroup message '((user-mail-address custom-variable)
45                     (user-full-name custom-variable))
46   "Mail and news message composing."
47   :link '(custom-manual "(message)Top")
48   :group 'mail
49   :group 'news)
50
51 (put 'user-mail-address 'custom-type 'string)
52 (put 'user-full-name 'custom-type 'string)
53
54 (defgroup message-various nil
55   "Various Message Variables"
56   :link '(custom-manual "(message)Various Message Variables")
57   :group 'message)
58
59 (defgroup message-buffers nil
60   "Message Buffers"
61   :link '(custom-manual "(message)Message Buffers")
62   :group 'message)
63
64 (defgroup message-sending nil
65   "Message Sending"
66   :link '(custom-manual "(message)Sending Variables")
67   :group 'message)
68
69 (defgroup message-interface nil
70   "Message Interface"
71   :link '(custom-manual "(message)Interface")
72   :group 'message)
73
74 (defgroup message-forwarding nil
75   "Message Forwarding"
76   :link '(custom-manual "(message)Forwarding")
77   :group 'message-interface)
78
79 (defgroup message-insertion nil
80   "Message Insertion"
81   :link '(custom-manual "(message)Insertion")
82   :group 'message)
83
84 (defgroup message-headers nil
85   "Message Headers"
86   :link '(custom-manual "(message)Message Headers")
87   :group 'message)
88
89 (defgroup message-news nil
90   "Composing News Messages"
91   :group 'message)
92
93 (defgroup message-mail nil
94   "Composing Mail Messages"
95   :group 'message)
96
97 (defgroup message-faces nil
98   "Faces used for message composing."
99   :group 'message
100   :group 'faces)
101
102 (defcustom message-directory "~/Mail/"
103   "*Directory from which all other mail file variables are derived."
104   :group 'message-various
105   :type 'directory)
106
107 (defcustom message-max-buffers 10
108   "*How many buffers to keep before starting to kill them off."
109   :group 'message-buffers
110   :type 'integer)
111
112 (defcustom message-send-rename-function nil
113   "Function called to rename the buffer after sending it."
114   :group 'message-buffers
115   :type '(choice function (const nil)))
116
117 (defcustom message-fcc-handler-function 'message-output
118   "*A function called to save outgoing articles.
119 This function will be called with the name of the file to store the
120 article in.  The default function is `message-output' which saves in Unix
121 mailbox format."
122   :type '(radio (function-item message-output)
123                 (function :tag "Other"))
124   :group 'message-sending)
125
126 (defcustom message-courtesy-message
127   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
128   "*This is inserted at the start of a mailed copy of a posted message.
129 If the string contains the format spec \"%s\", the Newsgroups
130 the article has been posted to will be inserted there.
131 If this variable is nil, no such courtesy message will be added."
132   :group 'message-sending
133   :type 'string)
134
135 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
136   "*Regexp that matches headers to be removed in resent bounced mail."
137   :group 'message-interface
138   :type 'regexp)
139
140 ;;;###autoload
141 (defcustom message-from-style 'default
142   "*Specifies how \"From\" headers look.
143
144 If nil, they contain just the return address like:
145         king@grassland.com
146 If `parens', they look like:
147         king@grassland.com (Elvis Parsley)
148 If `angles', they look like:
149         Elvis Parsley <king@grassland.com>
150
151 Otherwise, most addresses look like `angles', but they look like
152 `parens' if `angles' would need quoting and `parens' would not."
153   :type '(choice (const :tag "simple" nil)
154                  (const parens)
155                  (const angles)
156                  (const default))
157   :group 'message-headers)
158
159 (defcustom message-syntax-checks nil
160   ;; Guess this one shouldn't be easy to customize...
161   "*Controls what syntax checks should not be performed on outgoing posts.
162 To disable checking of long signatures, for instance, add
163  `(signature . disabled)' to this list.
164
165 Don't touch this variable unless you really know what you're doing.
166
167 Checks include `subject-cmsg', `multiple-headers', `sendsys',
168 `message-id', `from', `long-lines', `control-chars', `size',
169 `new-text', `quoting-style', `redirected-followup', `signature',
170 `approved', `sender', `empty', `empty-headers', `message-id', `from',
171 `subject', `shorten-followup-to', `existing-newsgroups',
172 `buffer-file-name', `unchanged', `newsgroups'."
173   :group 'message-news
174   :type '(repeat sexp))                 ; Fixme: improve this
175
176 (defcustom message-required-news-headers
177   '(From Newsgroups Subject Date Message-ID
178          (optional . Organization) Lines
179          (optional . User-Agent))
180   "*Headers to be generated or prompted for when posting an article.
181 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
182 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
183 User-Agent are optional.  If don't you want message to insert some
184 header, remove it from this list."
185   :group 'message-news
186   :group 'message-headers
187   :type '(repeat sexp))
188
189 (defcustom message-required-mail-headers
190   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
191          (optional . User-Agent))
192   "*Headers to be generated or prompted for when mailing a message.
193 RFC822 required that From, Date, To, Subject and Message-ID be
194 included.  Organization, Lines and User-Agent are optional."
195   :group 'message-mail
196   :group 'message-headers
197   :type '(repeat sexp))
198
199 (defcustom message-deletable-headers '(Message-ID Date Lines)
200   "Headers to be deleted if they already exist and were generated by message previously."
201   :group 'message-headers
202   :type 'sexp)
203
204 (defcustom message-ignored-news-headers
205   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|X-Draft-From:"
206   "*Regexp of headers to be removed unconditionally before posting."
207   :group 'message-news
208   :group 'message-headers
209   :type 'regexp)
210
211 (defcustom message-ignored-mail-headers
212   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|X-Draft-From:"
213   "*Regexp of headers to be removed unconditionally before mailing."
214   :group 'message-mail
215   :group 'message-headers
216   :type 'regexp)
217
218 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:"
219   "*Header lines matching this regexp will be deleted before posting.
220 It's best to delete old Path and Date headers before posting to avoid
221 any confusion."
222   :group 'message-interface
223   :type 'regexp)
224
225 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
226   "*Regexp matching \"Re: \" in the subject line."
227   :group 'message-various
228   :type 'regexp)
229
230 ;;;###autoload
231 (defcustom message-signature-separator "^-- *$"
232   "Regexp matching the signature separator."
233   :type 'regexp
234   :group 'message-various)
235
236 (defcustom message-elide-ellipsis "\n[...]\n\n"
237   "*The string which is inserted for elided text."
238   :type 'string
239   :group 'message-various)
240
241 (defcustom message-interactive nil
242   "Non-nil means when sending a message wait for and display errors.
243 nil means let mailer mail back a message to report errors."
244   :group 'message-sending
245   :group 'message-mail
246   :type 'boolean)
247
248 (defcustom message-generate-new-buffers 'unique
249   "*Non-nil means create a new message buffer whenever `message-setup' is called.
250 If this is a function, call that function with three parameters:  The type,
251 the to address and the group name.  (Any of these may be nil.)  The function
252 should return the new buffer name."
253   :group 'message-buffers
254   :type '(choice (const :tag "off" nil)
255                  (const :tag "unique" unique)
256                  (const :tag "unsent" unsent)
257                  (function fun)))
258
259 (defcustom message-kill-buffer-on-exit nil
260   "*Non-nil means that the message buffer will be killed after sending a message."
261   :group 'message-buffers
262   :type 'boolean)
263
264 (eval-when-compile
265   (defvar gnus-local-organization))
266 (defcustom message-user-organization
267   (or (and (boundp 'gnus-local-organization)
268            (stringp gnus-local-organization)
269            gnus-local-organization)
270       (getenv "ORGANIZATION")
271       t)
272   "*String to be used as an Organization header.
273 If t, use `message-user-organization-file'."
274   :group 'message-headers
275   :type '(choice string
276                  (const :tag "consult file" t)))
277
278 ;;;###autoload
279 (defcustom message-user-organization-file "/usr/lib/news/organization"
280   "*Local news organization file."
281   :type 'file
282   :group 'message-headers)
283
284 (defcustom message-make-forward-subject-function
285   'message-forward-subject-author-subject
286   "*List of functions called to generate subject headers for forwarded messages.
287 The subject generated by the previous function is passed into each
288 successive function.
289
290 The provided functions are:
291
292 * `message-forward-subject-author-subject' (Source of article (author or
293       newsgroup)), in brackets followed by the subject
294 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
295       to it."
296   :group 'message-forwarding
297   :type '(radio (function-item message-forward-subject-author-subject)
298                 (function-item message-forward-subject-fwd)
299                 (repeat :tag "List of functions" function)))
300
301 (defcustom message-forward-as-mime t
302   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
303   :version "21.1"
304   :group 'message-forwarding
305   :type 'boolean)
306
307 (defcustom message-forward-show-mml t
308   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
309   :version "21.1"
310   :group 'message-forwarding
311   :type 'boolean)
312
313 (defcustom message-forward-before-signature t
314   "*If non-nil, put forwarded message before signature, else after."
315   :group 'message-forwarding
316   :type 'boolean)
317
318 (defcustom message-wash-forwarded-subjects nil
319   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
320   :group 'message-forwarding
321   :type 'boolean)
322
323 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
324   "*All headers that match this regexp will be deleted when resending a message."
325   :group 'message-interface
326   :type 'regexp)
327
328 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
329   "*All headers that match this regexp will be deleted when forwarding a message."
330   :version "21.1"
331   :group 'message-forwarding
332   :type '(choice (const :tag "None" nil)
333                  regexp))
334
335 (defcustom message-ignored-cited-headers "."
336   "*Delete these headers from the messages you yank."
337   :group 'message-insertion
338   :type 'regexp)
339
340 (defcustom message-cite-prefix-regexp
341   ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
342   "\\([ \t]*\\(\\w\\|[-_.]\\)+>+\\|[ \t]*[]>»|:}+]\\)+"
343   "*Regexp matching the longest possible citation prefix on a line."
344   :group 'message-insertion
345   :type 'regexp)
346
347 (defcustom message-cancel-message "I am canceling my own article.\n"
348   "Message to be inserted in the cancel message."
349   :group 'message-interface
350   :type 'string)
351
352 ;; Useful to set in site-init.el
353 ;;;###autoload
354 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
355   "Function to call to send the current buffer as mail.
356 The headers should be delimited by a line whose contents match the
357 variable `mail-header-separator'.
358
359 Valid values include `message-send-mail-with-sendmail' (the default),
360 `message-send-mail-with-mh', `message-send-mail-with-qmail',
361 `smtpmail-send-it' and `feedmail-send-it'.
362
363 See also `send-mail-function'."
364   :type '(radio (function-item message-send-mail-with-sendmail)
365                 (function-item message-send-mail-with-mh)
366                 (function-item message-send-mail-with-qmail)
367                 (function-item smtpmail-send-it)
368                 (function-item feedmail-send-it)
369                 (function :tag "Other"))
370   :group 'message-sending
371   :group 'message-mail)
372
373 (defcustom message-send-news-function 'message-send-news
374   "Function to call to send the current buffer as news.
375 The headers should be delimited by a line whose contents match the
376 variable `mail-header-separator'."
377   :group 'message-sending
378   :group 'message-news
379   :type 'function)
380
381 (defcustom message-reply-to-function nil
382   "If non-nil, function that should return a list of headers.
383 This function should pick out addresses from the To, Cc, and From headers
384 and respond with new To and Cc headers."
385   :group 'message-interface
386   :type '(choice function (const nil)))
387
388 (defcustom message-wide-reply-to-function nil
389   "If non-nil, function that should return a list of headers.
390 This function should pick out addresses from the To, Cc, and From headers
391 and respond with new To and Cc headers."
392   :group 'message-interface
393   :type '(choice function (const nil)))
394
395 (defcustom message-followup-to-function nil
396   "If non-nil, function that should return a list of headers.
397 This function should pick out addresses from the To, Cc, and From headers
398 and respond with new To and Cc headers."
399   :group 'message-interface
400   :type '(choice function (const nil)))
401
402 (defcustom message-use-followup-to 'ask
403   "*Specifies what to do with Followup-To header.
404 If nil, always ignore the header.  If it is t, use its value, but
405 query before using the \"poster\" value.  If it is the symbol `ask',
406 always query the user whether to use the value.  If it is the symbol
407 `use', always use the value."
408   :group 'message-interface
409   :type '(choice (const :tag "ignore" nil)
410                  (const use)
411                  (const ask)))
412
413 (defcustom message-sendmail-f-is-evil nil
414   "*Non-nil means don't add \"-f username\" to the sendmail command line.
415 Doing so would be even more evil than leaving it out."
416   :group 'message-sending
417   :type 'boolean)
418
419 ;; qmail-related stuff
420 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
421   "Location of the qmail-inject program."
422   :group 'message-sending
423   :type 'file)
424
425 (defcustom message-qmail-inject-args nil
426   "Arguments passed to qmail-inject programs.
427 This should be a list of strings, one string for each argument.
428
429 For e.g., if you wish to set the envelope sender address so that bounces
430 go to the right place or to deal with listserv's usage of that address, you
431 might set this variable to '(\"-f\" \"you@some.where\")."
432   :group 'message-sending
433   :type '(repeat string))
434
435 (defvar message-cater-to-broken-inn t
436   "Non-nil means Gnus should not fold the `References' header.
437 Folding `References' makes ancient versions of INN create incorrect
438 NOV lines.")
439
440 (eval-when-compile
441   (defvar gnus-post-method)
442   (defvar gnus-select-method))
443 (defcustom message-post-method
444   (cond ((and (boundp 'gnus-post-method)
445               (listp gnus-post-method)
446               gnus-post-method)
447          gnus-post-method)
448         ((boundp 'gnus-select-method)
449          gnus-select-method)
450         (t '(nnspool "")))
451   "*Method used to post news.
452 Note that when posting from inside Gnus, for instance, this
453 variable isn't used."
454   :group 'message-news
455   :group 'message-sending
456   ;; This should be the `gnus-select-method' widget, but that might
457   ;; create a dependence to `gnus.el'.
458   :type 'sexp)
459
460 (defcustom message-generate-headers-first nil
461   "*If non-nil, generate all possible headers before composing."
462   :group 'message-headers
463   :type 'boolean)
464
465 (defcustom message-setup-hook nil
466   "Normal hook, run each time a new outgoing message is initialized.
467 The function `message-setup' runs this hook."
468   :group 'message-various
469   :type 'hook)
470
471 (defcustom message-cancel-hook nil
472   "Hook run when cancelling articles."
473   :group 'message-various
474   :type 'hook)
475
476 (defcustom message-signature-setup-hook nil
477   "Normal hook, run each time a new outgoing message is initialized.
478 It is run after the headers have been inserted and before
479 the signature is inserted."
480   :group 'message-various
481   :type 'hook)
482
483 (defcustom message-mode-hook nil
484   "Hook run in message mode buffers."
485   :group 'message-various
486   :type 'hook)
487
488 (defcustom message-header-hook nil
489   "Hook run in a message mode buffer narrowed to the headers."
490   :group 'message-various
491   :type 'hook)
492
493 (defcustom message-header-setup-hook nil
494   "Hook called narrowed to the headers when setting up a message buffer."
495   :group 'message-various
496   :type 'hook)
497
498 (defcustom message-minibuffer-local-map 
499   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
500     (set-keymap-parent map minibuffer-local-map)
501     map)
502   "Keymap for `message-read-from-minibuffer'.")
503
504 ;;;###autoload
505 (defcustom message-citation-line-function 'message-insert-citation-line
506   "*Function called to insert the \"Whomever writes:\" line."
507   :type 'function
508   :group 'message-insertion)
509
510 ;;;###autoload
511 (defcustom message-yank-prefix "> "
512   "*Prefix inserted on the lines of yanked messages.
513 Fix `message-cite-prefix-regexp' if it is set to an abnormal value."
514   :type 'string
515   :group 'message-insertion)
516
517 (defcustom message-indentation-spaces 3
518   "*Number of spaces to insert at the beginning of each cited line.
519 Used by `message-yank-original' via `message-yank-cite'."
520   :group 'message-insertion
521   :type 'integer)
522
523 ;;;###autoload
524 (defcustom message-cite-function 'message-cite-original
525   "*Function for citing an original message.
526 Predefined functions include `message-cite-original' and
527 `message-cite-original-without-signature'.
528 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
529   :type '(radio (function-item message-cite-original)
530                 (function-item message-cite-original-without-signature)
531                 (function-item sc-cite-original)
532                 (function :tag "Other"))
533   :group 'message-insertion)
534
535 ;;;###autoload
536 (defcustom message-indent-citation-function 'message-indent-citation
537   "*Function for modifying a citation just inserted in the mail buffer.
538 This can also be a list of functions.  Each function can find the
539 citation between (point) and (mark t).  And each function should leave
540 point and mark around the citation text as modified."
541   :type 'function
542   :group 'message-insertion)
543
544 (defvar message-abbrevs-loaded nil)
545
546 ;;;###autoload
547 (defcustom message-signature t
548   "*String to be inserted at the end of the message buffer.
549 If t, the `message-signature-file' file will be inserted instead.
550 If a function, the result from the function will be used instead.
551 If a form, the result from the form will be used instead."
552   :type 'sexp
553   :group 'message-insertion)
554
555 ;;;###autoload
556 (defcustom message-signature-file "~/.signature"
557   "*File containing the text inserted at end of message buffer."
558   :type 'file
559   :group 'message-insertion)
560
561 (defcustom message-distribution-function nil
562   "*Function called to return a Distribution header."
563   :group 'message-news
564   :group 'message-headers
565   :type '(choice function (const nil)))
566
567 (defcustom message-expires 14
568   "Number of days before your article expires."
569   :group 'message-news
570   :group 'message-headers
571   :link '(custom-manual "(message)News Headers")
572   :type 'integer)
573
574 (defcustom message-user-path nil
575   "If nil, use the NNTP server name in the Path header.
576 If stringp, use this; if non-nil, use no host name (user name only)."
577   :group 'message-news
578   :group 'message-headers
579   :link '(custom-manual "(message)News Headers")
580   :type '(choice (const :tag "nntp" nil)
581                  (string :tag "name")
582                  (sexp :tag "none" :format "%t" t)))
583
584 (defvar message-reply-buffer nil)
585 (defvar message-reply-headers nil)
586 (defvar message-newsreader nil)
587 (defvar message-mailer nil)
588 (defvar message-sent-message-via nil)
589 (defvar message-checksum nil)
590 (defvar message-send-actions nil
591   "A list of actions to be performed upon successful sending of a message.")
592 (defvar message-exit-actions nil
593   "A list of actions to be performed upon exiting after sending a message.")
594 (defvar message-kill-actions nil
595   "A list of actions to be performed before killing a message buffer.")
596 (defvar message-postpone-actions nil
597   "A list of actions to be performed after postponing a message.")
598
599 (define-widget 'message-header-lines 'text
600   "All header lines must be LFD terminated."
601   :format "%{%t%}:%n%v"
602   :valid-regexp "^\\'"
603   :error "All header lines must be newline terminated")
604
605 (defcustom message-default-headers ""
606   "*A string containing header lines to be inserted in outgoing messages.
607 It is inserted before you edit the message, so you can edit or delete
608 these lines."
609   :group 'message-headers
610   :type 'message-header-lines)
611
612 (defcustom message-default-mail-headers ""
613   "*A string of header lines to be inserted in outgoing mails."
614   :group 'message-headers
615   :group 'message-mail
616   :type 'message-header-lines)
617
618 (defcustom message-default-news-headers ""
619   "*A string of header lines to be inserted in outgoing news articles."
620   :group 'message-headers
621   :group 'message-news
622   :type 'message-header-lines)
623
624 ;; Note: could use /usr/ucb/mail instead of sendmail;
625 ;; options -t, and -v if not interactive.
626 (defcustom message-mailer-swallows-blank-line
627   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
628                          system-configuration)
629            (file-readable-p "/etc/sendmail.cf")
630            (let ((buffer (get-buffer-create " *temp*")))
631              (unwind-protect
632                  (save-excursion
633                    (set-buffer buffer)
634                    (insert-file-contents "/etc/sendmail.cf")
635                    (goto-char (point-min))
636                    (let ((case-fold-search nil))
637                      (re-search-forward "^OR\\>" nil t)))
638                (kill-buffer buffer))))
639       ;; According to RFC822, "The field-name must be composed of printable
640       ;; ASCII characters (i. e., characters that have decimal values between
641       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
642       ;; space, or colon.
643       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
644   "*Set this non-nil if the system's mailer runs the header and body together.
645 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
646 The value should be an expression to test whether the problem will
647 actually occur."
648   :group 'message-sending
649   :type 'sexp)
650
651 ;;;###autoload
652 (define-mail-user-agent 'message-user-agent
653   'message-mail 'message-send-and-exit
654   'message-kill-buffer 'message-send-hook)
655
656 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
657   "If non-nil, delete the deletable headers before feeding to mh.")
658
659 (defvar message-send-method-alist
660   '((news message-news-p message-send-via-news)
661     (mail message-mail-p message-send-via-mail))
662   "Alist of ways to send outgoing messages.
663 Each element has the form
664
665   \(TYPE PREDICATE FUNCTION)
666
667 where TYPE is a symbol that names the method; PREDICATE is a function
668 called without any parameters to determine whether the message is
669 a message of type TYPE; and FUNCTION is a function to be called if
670 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
671 the prefix.")
672
673 (defcustom message-mail-alias-type 'abbrev
674   "*What alias expansion type to use in Message buffers.
675 The default is `abbrev', which uses mailabbrev.  nil switches
676 mail aliases off."
677   :group 'message
678   :link '(custom-manual "(message)Mail Aliases")
679   :type '(choice (const :tag "Use Mailabbrev" abbrev)
680                  (const :tag "No expansion" nil)))
681
682 (defcustom message-auto-save-directory
683   (file-name-as-directory (nnheader-concat message-directory "drafts"))
684   "*Directory where Message auto-saves buffers if Gnus isn't running.
685 If nil, Message won't auto-save."
686   :group 'message-buffers
687   :type '(choice directory (const :tag "Don't auto-save" nil)))
688
689 (defcustom message-buffer-naming-style 'unique
690   "*The way new message buffers are named.
691 Valid valued are `unique' and `unsent'."
692   :version "21.1"
693   :group 'message-buffers
694   :type '(choice (const :tag "unique" unique)
695                  (const :tag "unsent" unsent)))
696
697 (defcustom message-default-charset
698   (and (not (mm-multibyte-p)) 'iso-8859-1)
699   "Default charset used in non-MULE Emacsen.
700 If nil, you might be asked to input the charset."
701   :version "21.1"
702   :group 'message
703   :type 'symbol)
704
705 (defcustom message-dont-reply-to-names
706   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
707   "*A regexp specifying names to prune when doing wide replies.
708 A value of nil means exclude your own name only."
709   :version "21.1"
710   :group 'message
711   :type '(choice (const :tag "Yourself" nil)
712                  regexp))
713
714 (defvar message-shoot-gnksa-feet nil
715   "*A list of GNKSA feet you are allowed to shoot.  
716 Gnus gives you all the opportunity you could possibly want for
717 shooting yourself in the foot.  Also, Gnus allows you to shoot the
718 feet of Good Net-Keeping Seal of Approval. The following are foot
719 candidates:
720 `empty-article'     Allow you to post an empty article;
721 `quoted-text-only'  Allow you to post quoted text only;
722 `multiple-copies'   Allow you to post multiple copies.")
723
724 (defsubst message-gnksa-enable-p (feature)
725   (or (not (listp message-shoot-gnksa-feet))
726       (memq feature message-shoot-gnksa-feet)))
727
728 ;;; Internal variables.
729 ;;; Well, not really internal.
730
731 (defvar message-mode-syntax-table
732   (let ((table (copy-syntax-table text-mode-syntax-table)))
733     (modify-syntax-entry ?% ". " table)
734     (modify-syntax-entry ?> ". " table)
735     (modify-syntax-entry ?< ". " table)
736     table)
737   "Syntax table used while in Message mode.")
738
739 (defvar message-mode-abbrev-table text-mode-abbrev-table
740   "Abbrev table used in Message mode buffers.
741 Defaults to `text-mode-abbrev-table'.")
742
743 (defface message-header-to-face
744   '((((class color)
745       (background dark))
746      (:foreground "green2" :bold t))
747     (((class color)
748       (background light))
749      (:foreground "MidnightBlue" :bold t))
750     (t
751      (:bold t :italic t)))
752   "Face used for displaying From headers."
753   :group 'message-faces)
754
755 (defface message-header-cc-face
756   '((((class color)
757       (background dark))
758      (:foreground "green4" :bold t))
759     (((class color)
760       (background light))
761      (:foreground "MidnightBlue"))
762     (t
763      (:bold t)))
764   "Face used for displaying Cc headers."
765   :group 'message-faces)
766
767 (defface message-header-subject-face
768   '((((class color)
769       (background dark))
770      (:foreground "green3"))
771     (((class color)
772       (background light))
773      (:foreground "navy blue" :bold t))
774     (t
775      (:bold t)))
776   "Face used for displaying subject headers."
777   :group 'message-faces)
778
779 (defface message-header-newsgroups-face
780   '((((class color)
781       (background dark))
782      (:foreground "yellow" :bold t :italic t))
783     (((class color)
784       (background light))
785      (:foreground "blue4" :bold t :italic t))
786     (t
787      (:bold t :italic t)))
788   "Face used for displaying newsgroups headers."
789   :group 'message-faces)
790
791 (defface message-header-other-face
792   '((((class color)
793       (background dark))
794      (:foreground "#b00000"))
795     (((class color)
796       (background light))
797      (:foreground "steel blue"))
798     (t
799      (:bold t :italic t)))
800   "Face used for displaying newsgroups headers."
801   :group 'message-faces)
802
803 (defface message-header-name-face
804   '((((class color)
805       (background dark))
806      (:foreground "DarkGreen"))
807     (((class color)
808       (background light))
809      (:foreground "cornflower blue"))
810     (t
811      (:bold t)))
812   "Face used for displaying header names."
813   :group 'message-faces)
814
815 (defface message-header-xheader-face
816   '((((class color)
817       (background dark))
818      (:foreground "blue"))
819     (((class color)
820       (background light))
821      (:foreground "blue"))
822     (t
823      (:bold t)))
824   "Face used for displaying X-Header headers."
825   :group 'message-faces)
826
827 (defface message-separator-face
828   '((((class color)
829       (background dark))
830      (:foreground "blue3"))
831     (((class color)
832       (background light))
833      (:foreground "brown"))
834     (t
835      (:bold t)))
836   "Face used for displaying the separator."
837   :group 'message-faces)
838
839 (defface message-cited-text-face
840   '((((class color)
841       (background dark))
842      (:foreground "red"))
843     (((class color)
844       (background light))
845      (:foreground "red"))
846     (t
847      (:bold t)))
848   "Face used for displaying cited text names."
849   :group 'message-faces)
850
851 (defface message-mml-face
852   '((((class color)
853       (background dark))
854      (:foreground "ForestGreen"))
855     (((class color)
856       (background light))
857      (:foreground "ForestGreen"))
858     (t
859      (:bold t)))
860   "Face used for displaying MML."
861   :group 'message-faces)
862
863 (defvar message-font-lock-keywords
864   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
865     `((,(concat "^\\([Tt]o:\\)" content)
866        (1 'message-header-name-face)
867        (2 'message-header-to-face nil t))
868       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
869        (1 'message-header-name-face)
870        (2 'message-header-cc-face nil t))
871       (,(concat "^\\([Ss]ubject:\\)" content)
872        (1 'message-header-name-face)
873        (2 'message-header-subject-face nil t))
874       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
875        (1 'message-header-name-face)
876        (2 'message-header-newsgroups-face nil t))
877       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
878        (1 'message-header-name-face)
879        (2 'message-header-other-face nil t))
880       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
881        (1 'message-header-name-face)
882        (2 'message-header-name-face))
883       ,@(if (and mail-header-separator
884                  (not (equal mail-header-separator "")))
885             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
886                1 'message-separator-face))
887           nil)
888       (,(concat "^\\(" message-cite-prefix-regexp "\\).*")
889        (0 'message-cited-text-face))
890       ("<#/?\\(multipart\\|part\\|external\\|mml\\).*>"
891        (0 'message-mml-face))))
892   "Additional expressions to highlight in Message mode.")
893
894 ;; XEmacs does it like this.  For Emacs, we have to set the
895 ;; `font-lock-defaults' buffer-local variable.
896 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
897
898 (defvar message-face-alist
899   '((bold . bold-region)
900     (underline . underline-region)
901     (default . (lambda (b e)
902                  (unbold-region b e)
903                  (ununderline-region b e))))
904   "Alist of mail and news faces for facemenu.
905 The cdr of ech entry is a function for applying the face to a region.")
906
907 (defcustom message-send-hook nil
908   "Hook run before sending messages."
909   :group 'message-various
910   :options '(ispell-message)
911   :type 'hook)
912
913 (defcustom message-send-mail-hook nil
914   "Hook run before sending mail messages."
915   :group 'message-various
916   :type 'hook)
917
918 (defcustom message-send-news-hook nil
919   "Hook run before sending news messages."
920   :group 'message-various
921   :type 'hook)
922
923 (defcustom message-sent-hook nil
924   "Hook run after sending messages."
925   :group 'message-various
926   :type 'hook)
927
928 (defvar message-send-coding-system 'binary
929   "Coding system to encode outgoing mail.")
930
931 (defvar message-draft-coding-system
932   mm-auto-save-coding-system
933   "Coding system to compose mail.")
934
935 (defcustom message-send-mail-partially-limit 1000000
936   "The limitation of messages sent as message/partial.
937 The lower bound of message size in characters, beyond which the message
938 should be sent in several parts.  If it is nil, the size is unlimited."
939   :version "21.1"
940   :group 'message-buffers
941   :type '(choice (const :tag "unlimited" nil)
942                  (integer 1000000)))
943
944 (defcustom message-alternative-emails nil
945   "A regexp to match the alternative email addresses.
946 The first matched address (not primary one) is used in the From field."
947   :group 'message-headers
948   :type '(choice (const :tag "Always use primary" nil)
949                  regexp))
950
951 (defcustom message-mail-user-agent nil
952   "Like `mail-user-agent'.
953 Except if it is nil, use Gnus native MUA; if it is t, use
954 `mail-user-agent'."
955   :type '(radio (const :tag "Gnus native"
956                        :format "%t\n"
957                        nil)
958                 (const :tag "`mail-user-agent'"
959                        :format "%t\n"
960                        t)
961                 (function-item :tag "Default Emacs mail"
962                                :format "%t\n"
963                                sendmail-user-agent)
964                 (function-item :tag "Emacs interface to MH"
965                                :format "%t\n"
966                                mh-e-user-agent)
967                 (function :tag "Other"))
968   :version "21.1"
969   :group 'message)
970
971 ;;; Internal variables.
972
973 (defvar message-sending-message "Sending...")
974 (defvar message-buffer-list nil)
975 (defvar message-this-is-news nil)
976 (defvar message-this-is-mail nil)
977 (defvar message-draft-article nil)
978 (defvar message-mime-part nil)
979 (defvar message-posting-charset nil)
980
981 ;; Byte-compiler warning
982 (eval-when-compile
983   (defvar gnus-active-hashtb)
984   (defvar gnus-read-active-file))
985
986 ;;; Regexp matching the delimiter of messages in UNIX mail format
987 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
988 ;;; of rmail.el's rmail-unix-mail-delimiter.
989 (defvar message-unix-mail-delimiter
990   (let ((time-zone-regexp
991          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
992                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
993                  "\\|"
994                  "\\) *")))
995     (concat
996      "From "
997
998      ;; Many things can happen to an RFC 822 mailbox before it is put into
999      ;; a `From' line.  The leading phrase can be stripped, e.g.
1000      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1001      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1002      ;; can be removed, e.g.
1003      ;;         From: joe@y.z (Joe      K
1004      ;;                 User)
1005      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1006      ;;         From: Joe User
1007      ;;                 <joe@y.z>
1008      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1009      ;; The mailbox can be removed or be replaced by white space, e.g.
1010      ;;         From: "Joe User"{space}{tab}
1011      ;;                 <joe@y.z>
1012      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1013      ;; where {space} and {tab} represent the Ascii space and tab characters.
1014      ;; We want to match the results of any of these manglings.
1015      ;; The following regexp rejects names whose first characters are
1016      ;; obviously bogus, but after that anything goes.
1017      "\\([^\0-\b\n-\r\^?].*\\)? "
1018
1019      ;; The time the message was sent.
1020      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1021      "\\([^\0-\r \^?]+\\) +"            ; month
1022      "\\([0-3]?[0-9]\\) +"              ; day of month
1023      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1024
1025      ;; Perhaps a time zone, specified by an abbreviation, or by a
1026      ;; numeric offset.
1027      time-zone-regexp
1028
1029      ;; The year.
1030      " \\([0-9][0-9]+\\) *"
1031
1032      ;; On some systems the time zone can appear after the year, too.
1033      time-zone-regexp
1034
1035      ;; Old uucp cruft.
1036      "\\(remote from .*\\)?"
1037
1038      "\n"))
1039   "Regexp matching the delimiter of messages in UNIX mail format.")
1040
1041 (defvar message-unsent-separator
1042   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1043           "^ *---+ +Returned message +---+ *$\\|"
1044           "^Start of returned message$\\|"
1045           "^ *---+ +Original message +---+ *$\\|"
1046           "^ *--+ +begin message +--+ *$\\|"
1047           "^ *---+ +Original message follows +---+ *$\\|"
1048           "^ *---+ +Undelivered message follows +---+ *$\\|"
1049           "^|? *---+ +Message text follows: +---+ *|?$")
1050   "A regexp that matches the separator before the text of a failed message.")
1051
1052 (defvar message-header-format-alist
1053   `((Newsgroups)
1054     (To . message-fill-address)
1055     (Cc . message-fill-address)
1056     (Subject)
1057     (In-Reply-To)
1058     (Fcc)
1059     (Bcc)
1060     (Date)
1061     (Organization)
1062     (Distribution)
1063     (Lines)
1064     (Expires)
1065     (Message-ID)
1066     (References . message-shorten-references)
1067     (User-Agent))
1068   "Alist used for formatting headers.")
1069
1070 (defvar message-options nil
1071   "Some saved answers when sending message.")
1072
1073 (eval-and-compile
1074   (autoload 'message-setup-toolbar "messagexmas")
1075   (autoload 'mh-new-draft-name "mh-comp")
1076   (autoload 'mh-send-letter "mh-comp")
1077   (autoload 'gnus-point-at-eol "gnus-util")
1078   (autoload 'gnus-point-at-bol "gnus-util")
1079   (autoload 'gnus-output-to-rmail "gnus-util")
1080   (autoload 'gnus-output-to-mail "gnus-util")
1081   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1082   (autoload 'nndraft-request-associate-buffer "nndraft")
1083   (autoload 'nndraft-request-expire-articles "nndraft")
1084   (autoload 'gnus-open-server "gnus-int")
1085   (autoload 'gnus-request-post "gnus-int")
1086   (autoload 'gnus-alive-p "gnus-util")
1087   (autoload 'gnus-group-name-charset "gnus-group")
1088   (autoload 'rmail-output "rmail"))
1089
1090 \f
1091
1092 ;;;
1093 ;;; Utility functions.
1094 ;;;
1095
1096 (defmacro message-y-or-n-p (question show &rest text)
1097   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1098   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1099
1100 (defmacro message-delete-line (&optional n)
1101   "Delete the current line (and the next N lines)."
1102   `(delete-region (progn (beginning-of-line) (point))
1103                   (progn (forward-line ,(or n 1)) (point))))
1104
1105 (defun message-unquote-tokens (elems)
1106   "Remove double quotes (\") from strings in list ELEMS."
1107   (mapcar (lambda (item)
1108             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1109               (setq item (concat (match-string 1 item)
1110                                  (match-string 2 item))))
1111             item)
1112           elems))
1113
1114 (defun message-tokenize-header (header &optional separator)
1115   "Split HEADER into a list of header elements.
1116 SEPARATOR is a string of characters to be used as separators.  \",\"
1117 is used by default."
1118   (if (not header)
1119       nil
1120     (let ((regexp (format "[%s]+" (or separator ",")))
1121           (beg 1)
1122           (first t)
1123           quoted elems paren)
1124       (save-excursion
1125         (message-set-work-buffer)
1126         (insert header)
1127         (goto-char (point-min))
1128         (while (not (eobp))
1129           (if first
1130               (setq first nil)
1131             (forward-char 1))
1132           (cond ((and (> (point) beg)
1133                       (or (eobp)
1134                           (and (looking-at regexp)
1135                                (not quoted)
1136                                (not paren))))
1137                  (push (buffer-substring beg (point)) elems)
1138                  (setq beg (match-end 0)))
1139                 ((eq (char-after) ?\")
1140                  (setq quoted (not quoted)))
1141                 ((and (eq (char-after) ?\()
1142                       (not quoted))
1143                  (setq paren t))
1144                 ((and (eq (char-after) ?\))
1145                       (not quoted))
1146                  (setq paren nil))))
1147         (nreverse elems)))))
1148
1149 (defun message-mail-file-mbox-p (file)
1150   "Say whether FILE looks like a Unix mbox file."
1151   (when (and (file-exists-p file)
1152              (file-readable-p file)
1153              (file-regular-p file))
1154     (with-temp-buffer
1155       (nnheader-insert-file-contents file)
1156       (goto-char (point-min))
1157       (looking-at message-unix-mail-delimiter))))
1158
1159 (defun message-fetch-field (header &optional not-all)
1160   "The same as `mail-fetch-field', only remove all newlines."
1161   (let* ((inhibit-point-motion-hooks t)
1162          (case-fold-search t)
1163          (value (mail-fetch-field header nil (not not-all))))
1164     (when value
1165       (while (string-match "\n[\t ]+" value)
1166         (setq value (replace-match " " t t value)))
1167       (set-text-properties 0 (length value) nil value)
1168       value)))
1169
1170 (defun message-narrow-to-field ()
1171   "Narrow the buffer to the header on the current line."
1172   (beginning-of-line)
1173   (narrow-to-region
1174    (point)
1175    (progn
1176      (forward-line 1)
1177      (if (re-search-forward "^[^ \n\t]" nil t)
1178          (progn
1179            (beginning-of-line)
1180            (point))
1181        (point-max))))
1182   (goto-char (point-min)))
1183
1184 (defun message-add-header (&rest headers)
1185   "Add the HEADERS to the message header, skipping those already present."
1186   (while headers
1187     (let (hclean)
1188       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1189         (error "Invalid header `%s'" (car headers)))
1190       (setq hclean (match-string 1 (car headers)))
1191       (save-restriction
1192         (message-narrow-to-headers)
1193         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1194           (goto-char (point-max))
1195           (if (string-match "\n$" (car headers))
1196               (insert (car headers))
1197             (insert (car headers) ?\n)))))
1198     (setq headers (cdr headers))))
1199
1200
1201 (defun message-fetch-reply-field (header)
1202   "Fetch field HEADER from the message we're replying to."
1203   (when (and message-reply-buffer
1204              (buffer-name message-reply-buffer))
1205     (save-excursion
1206       (set-buffer message-reply-buffer)
1207       (message-fetch-field header))))
1208
1209 (defun message-set-work-buffer ()
1210   (if (get-buffer " *message work*")
1211       (progn
1212         (set-buffer " *message work*")
1213         (erase-buffer))
1214     (set-buffer (get-buffer-create " *message work*"))
1215     (kill-all-local-variables)
1216     (mm-enable-multibyte)))
1217
1218 (defun message-functionp (form)
1219   "Return non-nil if FORM is funcallable."
1220   (or (and (symbolp form) (fboundp form))
1221       (and (listp form) (eq (car form) 'lambda))
1222       (byte-code-function-p form)))
1223
1224 (defun message-strip-list-identifiers (subject)
1225   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1226   (require 'gnus-sum)                   ; for gnus-list-identifiers
1227   (let ((regexp (if (stringp gnus-list-identifiers)
1228                     gnus-list-identifiers
1229                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1230     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1231                                 " *\\)\\)+\\(Re: +\\)?\\)") subject)
1232         (concat (substring subject 0 (match-beginning 1))
1233                 (or (match-string 3 subject)
1234                     (match-string 5 subject))
1235                 (substring subject
1236                            (match-end 1)))
1237       subject)))
1238
1239 (defun message-strip-subject-re (subject)
1240   "Remove \"Re:\" from subject lines in string SUBJECT."
1241   (if (string-match message-subject-re-regexp subject)
1242       (substring subject (match-end 0))
1243     subject))
1244
1245 (defun message-remove-header (header &optional is-regexp first reverse)
1246   "Remove HEADER in the narrowed buffer.
1247 If IS-REGEXP, HEADER is a regular expression.
1248 If FIRST, only remove the first instance of the header.
1249 Return the number of headers removed."
1250   (goto-char (point-min))
1251   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1252         (number 0)
1253         (case-fold-search t)
1254         last)
1255     (while (and (not (eobp))
1256                 (not last))
1257       (if (if reverse
1258               (not (looking-at regexp))
1259             (looking-at regexp))
1260           (progn
1261             (incf number)
1262             (when first
1263               (setq last t))
1264             (delete-region
1265              (point)
1266              ;; There might be a continuation header, so we have to search
1267              ;; until we find a new non-continuation line.
1268              (progn
1269                (forward-line 1)
1270                (if (re-search-forward "^[^ \t]" nil t)
1271                    (goto-char (match-beginning 0))
1272                  (point-max)))))
1273         (forward-line 1)
1274         (if (re-search-forward "^[^ \t]" nil t)
1275             (goto-char (match-beginning 0))
1276           (goto-char (point-max)))))
1277     number))
1278
1279 (defun message-remove-first-header (header)
1280   "Remove the first instance of HEADER if there is more than one."
1281   (let ((count 0)
1282         (regexp (concat "^" (regexp-quote header) ":")))
1283     (save-excursion
1284       (goto-char (point-min))
1285       (while (re-search-forward regexp nil t)
1286         (incf count)))
1287     (while (> count 1)
1288       (message-remove-header header nil t)
1289       (decf count))))
1290
1291 (defun message-narrow-to-headers ()
1292   "Narrow the buffer to the head of the message."
1293   (widen)
1294   (narrow-to-region
1295    (goto-char (point-min))
1296    (if (re-search-forward
1297         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1298        (match-beginning 0)
1299      (point-max)))
1300   (goto-char (point-min)))
1301
1302 (defun message-narrow-to-head-1 ()
1303   "Like `message-narrow-to-head'.  Don't widen."
1304   (narrow-to-region
1305    (goto-char (point-min))
1306    (if (search-forward "\n\n" nil 1)
1307        (1- (point))
1308      (point-max)))
1309   (goto-char (point-min)))
1310
1311 (defun message-narrow-to-head ()
1312   "Narrow the buffer to the head of the message.
1313 Point is left at the beginning of the narrowed-to region."
1314   (widen)
1315   (message-narrow-to-head-1))
1316
1317 (defun message-narrow-to-headers-or-head ()
1318   "Narrow the buffer to the head of the message."
1319   (widen)
1320   (narrow-to-region
1321    (goto-char (point-min))
1322    (cond
1323     ((re-search-forward
1324       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1325      (match-beginning 0))
1326     ((search-forward "\n\n" nil t)
1327      (1- (point)))
1328     (t
1329      (point-max))))
1330   (goto-char (point-min)))
1331
1332 (defun message-news-p ()
1333   "Say whether the current buffer contains a news message."
1334   (and (not message-this-is-mail)
1335        (or message-this-is-news
1336            (save-excursion
1337              (save-restriction
1338                (message-narrow-to-headers)
1339                (and (message-fetch-field "newsgroups")
1340                     (not (message-fetch-field "posted-to"))))))))
1341
1342 (defun message-mail-p ()
1343   "Say whether the current buffer contains a mail message."
1344   (and (not message-this-is-news)
1345        (or message-this-is-mail
1346            (save-excursion
1347              (save-restriction
1348                (message-narrow-to-headers)
1349                (or (message-fetch-field "to")
1350                    (message-fetch-field "cc")
1351                    (message-fetch-field "bcc")))))))
1352
1353 (defun message-next-header ()
1354   "Go to the beginning of the next header."
1355   (beginning-of-line)
1356   (or (eobp) (forward-char 1))
1357   (not (if (re-search-forward "^[^ \t]" nil t)
1358            (beginning-of-line)
1359          (goto-char (point-max)))))
1360
1361 (defun message-sort-headers-1 ()
1362   "Sort the buffer as headers using `message-rank' text props."
1363   (goto-char (point-min))
1364   (require 'sort)
1365   (sort-subr
1366    nil 'message-next-header
1367    (lambda ()
1368      (message-next-header)
1369      (unless (bobp)
1370        (forward-char -1)))
1371    (lambda ()
1372      (or (get-text-property (point) 'message-rank)
1373          10000))))
1374
1375 (defun message-sort-headers ()
1376   "Sort the headers of the current message according to `message-header-format-alist'."
1377   (interactive)
1378   (save-excursion
1379     (save-restriction
1380       (let ((max (1+ (length message-header-format-alist)))
1381             rank)
1382         (message-narrow-to-headers)
1383         (while (re-search-forward "^[^ \n]+:" nil t)
1384           (put-text-property
1385            (match-beginning 0) (1+ (match-beginning 0))
1386            'message-rank
1387            (if (setq rank (length (memq (assq (intern (buffer-substring
1388                                                        (match-beginning 0)
1389                                                        (1- (match-end 0))))
1390                                               message-header-format-alist)
1391                                         message-header-format-alist)))
1392                (- max rank)
1393              (1+ max)))))
1394       (message-sort-headers-1))))
1395
1396 \f
1397
1398 ;;;
1399 ;;; Message mode
1400 ;;;
1401
1402 ;;; Set up keymap.
1403
1404 (defvar message-mode-map nil)
1405
1406 (unless message-mode-map
1407   (setq message-mode-map (make-keymap))
1408   (set-keymap-parent message-mode-map text-mode-map)
1409   (define-key message-mode-map "\C-c?" 'describe-mode)
1410
1411   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1412   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1413   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1414   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1415   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1416   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1417   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1418   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1419   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1420   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1421   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1422   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1423   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1424
1425   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1426   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1427
1428   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1429   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1430   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1431   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1432   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1433   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1434   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1435   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1436
1437   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1438   (define-key message-mode-map "\C-c\C-s" 'message-send)
1439   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1440   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1441
1442   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1443   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1444   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1445   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1446   (define-key message-mode-map "\M-q" 'message-fill-paragraph)
1447
1448   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1449
1450   (define-key message-mode-map "\t" 'message-tab)
1451   (define-key message-mode-map "\M-;" 'comment-region))
1452
1453 (easy-menu-define
1454  message-mode-menu message-mode-map "Message Menu."
1455  `("Message"
1456    ["Sort Headers" message-sort-headers t]
1457    ["Yank Original" message-yank-original t]
1458    ["Fill Yanked Message" message-fill-yanked-message t]
1459    ["Insert Signature" message-insert-signature t]
1460    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1461    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1462    ["Elide Region" message-elide-region (mark t)]
1463    ["Delete Outside Region" message-delete-not-region (mark t)]
1464    ["Kill To Signature" message-kill-to-signature t]
1465    ["Newline and Reformat" message-newline-and-reformat t]
1466    ["Rename buffer" message-rename-buffer t]
1467    ["Spellcheck" ispell-message
1468     ,@(if (featurep 'xemacs) nil
1469         '(:help "Spellcheck this message"))]
1470    ["Attach file as MIME" mml-attach-file
1471     ,@(if (featurep 'xemacs) nil
1472         '(:help "Attach a file at point"))]
1473    "----"
1474    ["Send Message" message-send-and-exit
1475     ,@(if (featurep 'xemacs) nil
1476         '(:help "Send this message"))]
1477    ["Abort Message" message-dont-send
1478     ,@(if (featurep 'xemacs) nil
1479         '(:help "File this draft message and exit"))]
1480    ["Kill Message" message-kill-buffer
1481     ,@(if (featurep 'xemacs) nil
1482         '(:help "Delete this message without sending"))]))
1483
1484 (easy-menu-define
1485  message-mode-field-menu message-mode-map ""
1486  '("Field"
1487    ["Fetch To" message-insert-to t]
1488    ["Fetch Newsgroups" message-insert-newsgroups t]
1489    "----"
1490    ["To" message-goto-to t]
1491    ["Subject" message-goto-subject t]
1492    ["Cc" message-goto-cc t]
1493    ["Reply-To" message-goto-reply-to t]
1494    ["Summary" message-goto-summary t]
1495    ["Keywords" message-goto-keywords t]
1496    ["Newsgroups" message-goto-newsgroups t]
1497    ["Followup-To" message-goto-followup-to t]
1498    ["Distribution" message-goto-distribution t]
1499    ["Body" message-goto-body t]
1500    ["Signature" message-goto-signature t]))
1501
1502 (defvar message-tool-bar-map nil)
1503
1504 (eval-when-compile
1505   (defvar facemenu-add-face-function)
1506   (defvar facemenu-remove-face-function))
1507
1508 ;;;###autoload
1509 (defun message-mode ()
1510   "Major mode for editing mail and news to be sent.
1511 Like Text Mode but with these additional commands:\\<message-mode-map>
1512 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1513 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1514 C-c C-f  move to a header field (and create it if there isn't):
1515          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1516          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1517          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1518          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1519          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1520          C-c C-f C-f  move to Followup-To
1521 C-c C-t  `message-insert-to' (add a To header to a news followup)
1522 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
1523 C-c C-b  `message-goto-body' (move to beginning of message text).
1524 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
1525 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
1526 C-c C-y  `message-yank-original' (insert current message, if any).
1527 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
1528 C-c C-e  `message-elide-region' (elide the text between point and mark).
1529 C-c C-v  `message-delete-not-region' (remove the text outside the region).
1530 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
1531 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
1532 C-c C-a  `mml-attach-file' (attach a file as MIME).
1533 M-RET    `message-newline-and-reformat' (break the line and reformat)."
1534   (interactive)
1535   (if (local-variable-p 'mml-buffer-list (current-buffer))
1536       (mml-destroy-buffers))
1537   (kill-all-local-variables)
1538   (set (make-local-variable 'message-reply-buffer) nil)
1539   (make-local-variable 'message-send-actions)
1540   (make-local-variable 'message-exit-actions)
1541   (make-local-variable 'message-kill-actions)
1542   (make-local-variable 'message-postpone-actions)
1543   (make-local-variable 'message-draft-article)
1544   (make-local-hook 'kill-buffer-hook)
1545   (set-syntax-table message-mode-syntax-table)
1546   (use-local-map message-mode-map)
1547   (setq local-abbrev-table message-mode-abbrev-table)
1548   (setq major-mode 'message-mode)
1549   (setq mode-name "Message")
1550   (setq buffer-offer-save t)
1551   (make-local-variable 'facemenu-add-face-function)
1552   (make-local-variable 'facemenu-remove-face-function)
1553   (setq facemenu-add-face-function
1554         (lambda (face end)
1555           (let ((face-fun (cdr (assq face message-face-alist))))
1556             (if face-fun
1557                 (funcall face-fun (point) end)
1558               (error "Face %s not configured for %s mode" face mode-name)))
1559           "")
1560         facemenu-remove-face-function t)
1561   (make-local-variable 'message-reply-headers)
1562   (setq message-reply-headers nil)
1563   (make-local-variable 'message-newsreader)
1564   (make-local-variable 'message-mailer)
1565   (make-local-variable 'message-post-method)
1566   (set (make-local-variable 'message-sent-message-via) nil)
1567   (set (make-local-variable 'message-checksum) nil)
1568   (set (make-local-variable 'message-mime-part) 0)
1569   (message-setup-fill-variables)
1570   ;; Allow using comment commands to add/remove quoting.
1571   (set (make-local-variable 'comment-start) message-yank-prefix)
1572   (if (featurep 'xemacs)
1573       (message-setup-toolbar)
1574     (set (make-local-variable 'font-lock-defaults)
1575          '(message-font-lock-keywords t))
1576     (if (boundp 'tool-bar-map)
1577         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1578   (easy-menu-add message-mode-menu message-mode-map)
1579   (easy-menu-add message-mode-field-menu message-mode-map)
1580   ;; Allow mail alias things.
1581   (when (eq message-mail-alias-type 'abbrev)
1582     (if (fboundp 'mail-abbrevs-setup)
1583         (mail-abbrevs-setup)
1584       (mail-aliases-setup)))
1585   (message-set-auto-save-file-name)
1586   (mm-enable-multibyte)
1587   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1588   (setq indent-tabs-mode nil)
1589   (mml-mode)
1590   (run-hooks 'text-mode-hook 'message-mode-hook))
1591
1592 (defun message-setup-fill-variables ()
1593   "Setup message fill variables."
1594   (make-local-variable 'paragraph-separate)
1595   (make-local-variable 'paragraph-start)
1596   (make-local-variable 'adaptive-fill-regexp)
1597   (unless (boundp 'adaptive-fill-first-line-regexp)
1598     (setq adaptive-fill-first-line-regexp nil))
1599   (make-local-variable 'adaptive-fill-first-line-regexp)
1600   (make-local-variable 'auto-fill-inhibit-regexp)
1601   (let ((quote-prefix-regexp
1602          ;; User should change message-cite-prefix-regexp if
1603          ;; message-yank-prefix is set to an abnormal value.
1604          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))      
1605     (setq paragraph-start
1606           (concat
1607            (regexp-quote mail-header-separator) "$\\|"
1608            "[ \t]*$\\|"                 ; blank lines
1609            "-- $\\|"                    ; signature delimiter
1610            "---+$\\|"                   ; delimiters for forwarded messages
1611            page-delimiter "$\\|"        ; spoiler warnings
1612            ".*wrote:$\\|"               ; attribution lines
1613            quote-prefix-regexp "$"))    ; empty lines in quoted text
1614     (setq paragraph-separate paragraph-start)
1615     (setq adaptive-fill-regexp
1616           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1617     (setq adaptive-fill-first-line-regexp
1618           (concat quote-prefix-regexp "\\|"
1619                   adaptive-fill-first-line-regexp))
1620     (setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")))
1621
1622 \f
1623
1624 ;;;
1625 ;;; Message mode commands
1626 ;;;
1627
1628 ;;; Movement commands
1629
1630 (defun message-goto-to ()
1631   "Move point to the To header."
1632   (interactive)
1633   (message-position-on-field "To"))
1634
1635 (defun message-goto-subject ()
1636   "Move point to the Subject header."
1637   (interactive)
1638   (message-position-on-field "Subject"))
1639
1640 (defun message-goto-cc ()
1641   "Move point to the Cc header."
1642   (interactive)
1643   (message-position-on-field "Cc" "To"))
1644
1645 (defun message-goto-bcc ()
1646   "Move point to the Bcc  header."
1647   (interactive)
1648   (message-position-on-field "Bcc" "Cc" "To"))
1649
1650 (defun message-goto-fcc ()
1651   "Move point to the Fcc header."
1652   (interactive)
1653   (message-position-on-field "Fcc" "To" "Newsgroups"))
1654
1655 (defun message-goto-reply-to ()
1656   "Move point to the Reply-To header."
1657   (interactive)
1658   (message-position-on-field "Reply-To" "Subject"))
1659
1660 (defun message-goto-newsgroups ()
1661   "Move point to the Newsgroups header."
1662   (interactive)
1663   (message-position-on-field "Newsgroups"))
1664
1665 (defun message-goto-distribution ()
1666   "Move point to the Distribution header."
1667   (interactive)
1668   (message-position-on-field "Distribution"))
1669
1670 (defun message-goto-followup-to ()
1671   "Move point to the Followup-To header."
1672   (interactive)
1673   (message-position-on-field "Followup-To" "Newsgroups"))
1674
1675 (defun message-goto-keywords ()
1676   "Move point to the Keywords header."
1677   (interactive)
1678   (message-position-on-field "Keywords" "Subject"))
1679
1680 (defun message-goto-summary ()
1681   "Move point to the Summary header."
1682   (interactive)
1683   (message-position-on-field "Summary" "Subject"))
1684
1685 (defun message-goto-body (&optional interactivep)
1686   "Move point to the beginning of the message body."
1687   (interactive (list t))
1688   (when (and interactivep
1689              (looking-at "[ \t]*\n"))
1690     (expand-abbrev))
1691   (goto-char (point-min))
1692   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1693       (search-forward "\n\n" nil t)))
1694
1695 (defun message-goto-eoh ()
1696   "Move point to the end of the headers."
1697   (interactive)
1698   (message-goto-body)
1699   (forward-line -1))
1700
1701 (defun message-goto-signature ()
1702   "Move point to the beginning of the message signature.
1703 If there is no signature in the article, go to the end and
1704 return nil."
1705   (interactive)
1706   (goto-char (point-min))
1707   (if (re-search-forward message-signature-separator nil t)
1708       (forward-line 1)
1709     (goto-char (point-max))
1710     nil))
1711
1712 \f
1713
1714 (defun message-insert-to (&optional force)
1715   "Insert a To header that points to the author of the article being replied to.
1716 If the original author requested not to be sent mail, the function signals
1717 an error.
1718 With the prefix argument FORCE, insert the header anyway."
1719   (interactive "P")
1720   (let ((co (message-fetch-reply-field "mail-copies-to")))
1721     (when (and (null force)
1722                co
1723                (or (equal (downcase co) "never")
1724                    (equal (downcase co) "nobody")))
1725       (error "The user has requested not to have copies sent via mail")))
1726   (when (and (message-position-on-field "To")
1727              (mail-fetch-field "to")
1728              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1729     (insert ", "))
1730   (insert (or (message-fetch-reply-field "mail-reply-to")
1731               (message-fetch-reply-field "reply-to")
1732               (message-fetch-reply-field "from") "")))
1733
1734 (defun message-widen-reply ()
1735   "Widen the reply to include maximum recipients."
1736   (interactive)
1737   (let ((follow-to
1738          (and message-reply-buffer
1739               (buffer-name message-reply-buffer)
1740               (save-excursion
1741                 (set-buffer message-reply-buffer)
1742                 (message-get-reply-headers t)))))
1743     (save-excursion
1744       (save-restriction
1745         (message-narrow-to-headers)
1746         (dolist (elem follow-to)
1747           (message-remove-header (symbol-name (car elem)))
1748           (goto-char (point-min))
1749           (insert (symbol-name (car elem)) ": "
1750                   (cdr elem) "\n"))))))
1751
1752 (defun message-insert-newsgroups ()
1753   "Insert the Newsgroups header from the article being replied to."
1754   (interactive)
1755   (when (and (message-position-on-field "Newsgroups")
1756              (mail-fetch-field "newsgroups")
1757              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1758     (insert ","))
1759   (insert (or (message-fetch-reply-field "newsgroups") "")))
1760
1761 \f
1762
1763 ;;; Various commands
1764
1765 (defun message-delete-not-region (beg end)
1766   "Delete everything in the body of the current message outside of the region."
1767   (interactive "r")
1768   (save-excursion
1769     (goto-char end)
1770     (delete-region (point) (if (not (message-goto-signature))
1771                                (point)
1772                              (forward-line -2)
1773                              (point)))
1774     (insert "\n")
1775     (goto-char beg)
1776     (delete-region beg (progn (message-goto-body)
1777                               (forward-line 2)
1778                               (point))))
1779   (when (message-goto-signature)
1780     (forward-line -2)))
1781
1782 (defun message-kill-to-signature ()
1783   "Deletes all text up to the signature."
1784   (interactive)
1785   (let ((point (point)))
1786     (message-goto-signature)
1787     (unless (eobp)
1788       (forward-line -2))
1789     (kill-region point (point))
1790     (unless (bolp)
1791       (insert "\n"))))
1792
1793 (defun message-newline-and-reformat (&optional not-break)
1794   "Insert four newlines, and then reformat if inside quoted text."
1795   (interactive)
1796   (let (quoted point beg end leading-space)
1797     (setq point (point))
1798     (beginning-of-line)
1799     (setq beg (point))
1800     ;; Find first line of the paragraph.
1801     (if not-break
1802         (while (and (not (eobp)) 
1803                     (not (looking-at message-cite-prefix-regexp))
1804                 (looking-at paragraph-start))
1805           (forward-line 1)))
1806     ;; Find the prefix
1807     (when (looking-at message-cite-prefix-regexp)
1808       (setq quoted (match-string 0))
1809       (goto-char (match-end 0))
1810       (looking-at "[ \t]*")
1811       (setq leading-space (match-string 0)))
1812     (if (and quoted
1813              (not not-break)
1814              (< (- point beg) (length quoted)))
1815         ;; break in the cite prefix.
1816         (setq quoted nil
1817               end nil))
1818     (if quoted
1819         (progn
1820           (forward-line 1)
1821           (while (and (not (eobp))
1822                       (not (looking-at paragraph-separate))
1823                       (looking-at message-cite-prefix-regexp)
1824                       (equal quoted (match-string 0)))
1825             (goto-char (match-end 0))
1826             (looking-at "[ \t]*")
1827             (if (> (length leading-space) (length (match-string 0)))
1828                 (setq leading-space (match-string 0)))
1829             (forward-line 1))
1830           (setq end (point))
1831           (goto-char beg)
1832           (while (and (if (bobp) nil (forward-line -1) t)
1833                       (not (looking-at paragraph-start))
1834                       (looking-at message-cite-prefix-regexp)
1835                       (equal quoted (match-string 0)))
1836             (setq beg (point))
1837             (goto-char (match-end 0))
1838             (looking-at "[ \t]*")
1839             (if (> (length leading-space) (length (match-string 0)))
1840                 (setq leading-space (match-string 0)))))
1841       (while (and (not (eobp))
1842                   (not (looking-at paragraph-separate))
1843                   (not (looking-at message-cite-prefix-regexp)))
1844         (forward-line 1))
1845       (setq end (point))
1846       (goto-char beg)
1847       (while (and (if (bobp) nil (forward-line -1) t)
1848                   (not (looking-at paragraph-start))
1849                   (not (looking-at message-cite-prefix-regexp)))
1850         (setq beg (point))))
1851     (goto-char point)
1852     (save-restriction
1853       (narrow-to-region beg end)
1854       (if not-break
1855           (setq point nil)
1856         (insert "\n\n")
1857         (setq point (point))
1858         (insert "\n\n")
1859         (delete-region (point) (re-search-forward "[ \t]*"))
1860         (when quoted
1861           (insert quoted leading-space)))
1862       (if quoted
1863           (let* ((adaptive-fill-regexp 
1864                  (regexp-quote (concat quoted leading-space)))
1865                  (adaptive-fill-first-line-regexp 
1866                   adaptive-fill-regexp ))
1867             (fill-paragraph nil))
1868         (fill-paragraph nil))
1869       (if point (goto-char point)))))
1870
1871 (defun message-fill-paragraph ()
1872   "Like `fill-paragraph'."
1873   (interactive)
1874   (message-newline-and-reformat t))
1875
1876 (defun message-insert-signature (&optional force)
1877   "Insert a signature.  See documentation for variable `message-signature'."
1878   (interactive (list 0))
1879   (let* ((signature
1880           (cond
1881            ((and (null message-signature)
1882                  (eq force 0))
1883             (save-excursion
1884               (goto-char (point-max))
1885               (not (re-search-backward message-signature-separator nil t))))
1886            ((and (null message-signature)
1887                  force)
1888             t)
1889            ((message-functionp message-signature)
1890             (funcall message-signature))
1891            ((listp message-signature)
1892             (eval message-signature))
1893            (t message-signature)))
1894          (signature
1895           (cond ((stringp signature)
1896                  signature)
1897                 ((and (eq t signature)
1898                       message-signature-file
1899                       (file-exists-p message-signature-file))
1900                  signature))))
1901     (when signature
1902       (goto-char (point-max))
1903       ;; Insert the signature.
1904       (unless (bolp)
1905         (insert "\n"))
1906       (insert "\n-- \n")
1907       (if (eq signature t)
1908           (insert-file-contents message-signature-file)
1909         (insert signature))
1910       (goto-char (point-max))
1911       (or (bolp) (insert "\n")))))
1912
1913 (defun message-elide-region (b e)
1914   "Elide the text in the region.
1915 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1916 text was killed."
1917   (interactive "r")
1918   (kill-region b e)
1919   (insert message-elide-ellipsis))
1920
1921 (defvar message-caesar-translation-table nil)
1922
1923 (defun message-caesar-region (b e &optional n)
1924   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
1925   (interactive
1926    (list
1927     (min (point) (or (mark t) (point)))
1928     (max (point) (or (mark t) (point)))
1929     (when current-prefix-arg
1930       (prefix-numeric-value current-prefix-arg))))
1931
1932   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1933   (unless (or (zerop n)                 ; no action needed for a rot of 0
1934               (= b e))                  ; no region to rotate
1935     ;; We build the table, if necessary.
1936     (when (or (not message-caesar-translation-table)
1937               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1938       (setq message-caesar-translation-table
1939             (message-make-caesar-translation-table n)))
1940     (translate-region b e message-caesar-translation-table)))
1941
1942 (defun message-make-caesar-translation-table (n)
1943   "Create a rot table with offset N."
1944   (let ((i -1)
1945         (table (make-string 256 0)))
1946     (while (< (incf i) 256)
1947       (aset table i i))
1948     (concat
1949      (substring table 0 ?A)
1950      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1951      (substring table ?A (+ ?A n))
1952      (substring table (+ ?A 26) ?a)
1953      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1954      (substring table ?a (+ ?a n))
1955      (substring table (+ ?a 26) 255))))
1956
1957 (defun message-caesar-buffer-body (&optional rotnum)
1958   "Caesar rotate all letters in the current buffer by 13 places.
1959 Used to encode/decode possibly offensive messages (commonly in rec.humor).
1960 With prefix arg, specifies the number of places to rotate each letter forward.
1961 Mail and USENET news headers are not rotated."
1962   (interactive (if current-prefix-arg
1963                    (list (prefix-numeric-value current-prefix-arg))
1964                  (list nil)))
1965   (save-excursion
1966     (save-restriction
1967       (when (message-goto-body)
1968         (narrow-to-region (point) (point-max)))
1969       (message-caesar-region (point-min) (point-max) rotnum))))
1970
1971 (defun message-pipe-buffer-body (program)
1972   "Pipe the message body in the current buffer through PROGRAM."
1973   (save-excursion
1974     (save-restriction
1975       (when (message-goto-body)
1976         (narrow-to-region (point) (point-max)))
1977       (shell-command-on-region
1978        (point-min) (point-max) program nil t))))
1979
1980 (defun message-rename-buffer (&optional enter-string)
1981   "Rename the *message* buffer to \"*message* RECIPIENT\".
1982 If the function is run with a prefix, it will ask for a new buffer
1983 name, rather than giving an automatic name."
1984   (interactive "Pbuffer name: ")
1985   (save-excursion
1986     (save-restriction
1987       (goto-char (point-min))
1988       (narrow-to-region (point)
1989                         (search-forward mail-header-separator nil 'end))
1990       (let* ((mail-to (or
1991                        (if (message-news-p) (message-fetch-field "Newsgroups")
1992                          (message-fetch-field "To"))
1993                        ""))
1994              (mail-trimmed-to
1995               (if (string-match "," mail-to)
1996                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1997                 mail-to))
1998              (name-default (concat "*message* " mail-trimmed-to))
1999              (name (if enter-string
2000                        (read-string "New buffer name: " name-default)
2001                      name-default)))
2002         (rename-buffer name t)))))
2003
2004 (defun message-fill-yanked-message (&optional justifyp)
2005   "Fill the paragraphs of a message yanked into this one.
2006 Numeric argument means justify as well."
2007   (interactive "P")
2008   (save-excursion
2009     (goto-char (point-min))
2010     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2011     (let ((fill-prefix message-yank-prefix))
2012       (fill-individual-paragraphs (point) (point-max) justifyp))))
2013
2014 (defun message-indent-citation ()
2015   "Modify text just inserted from a message to be cited.
2016 The inserted text should be the region.
2017 When this function returns, the region is again around the modified text.
2018
2019 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2020 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2021   (let ((start (point)))
2022     ;; Remove unwanted headers.
2023     (when message-ignored-cited-headers
2024       (let (all-removed)
2025         (save-restriction
2026           (narrow-to-region
2027            (goto-char start)
2028            (if (search-forward "\n\n" nil t)
2029                (1- (point))
2030              (point)))
2031           (message-remove-header message-ignored-cited-headers t)
2032           (when (= (point-min) (point-max))
2033             (setq all-removed t))
2034           (goto-char (point-max)))
2035         (if all-removed
2036             (goto-char start)
2037           (forward-line 1))))
2038     ;; Delete blank lines at the start of the buffer.
2039     (while (and (point-min)
2040                 (eolp)
2041                 (not (eobp)))
2042       (message-delete-line))
2043     ;; Delete blank lines at the end of the buffer.
2044     (goto-char (point-max))
2045     (unless (eolp)
2046       (insert "\n"))
2047     (while (and (zerop (forward-line -1))
2048                 (looking-at "$"))
2049       (message-delete-line))
2050     ;; Do the indentation.
2051     (if (null message-yank-prefix)
2052         (indent-rigidly start (mark t) message-indentation-spaces)
2053       (save-excursion
2054         (goto-char start)
2055         (while (< (point) (mark t))
2056           (insert message-yank-prefix)
2057           (forward-line 1))))
2058     (goto-char start)))
2059
2060 (defun message-yank-original (&optional arg)
2061   "Insert the message being replied to, if any.
2062 Puts point before the text and mark after.
2063 Normally indents each nonblank line ARG spaces (default 3).  However,
2064 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2065
2066 This function uses `message-cite-function' to do the actual citing.
2067
2068 Just \\[universal-argument] as argument means don't indent, insert no
2069 prefix, and don't delete any headers."
2070   (interactive "P")
2071   (let ((modified (buffer-modified-p)))
2072     (when (and message-reply-buffer
2073                message-cite-function)
2074       (delete-windows-on message-reply-buffer t)
2075       (insert-buffer message-reply-buffer)
2076       (funcall message-cite-function)
2077       (message-exchange-point-and-mark)
2078       (unless (bolp)
2079         (insert ?\n))
2080       (unless modified
2081         (setq message-checksum (message-checksum))))))
2082
2083 (defun message-yank-buffer (buffer)
2084   "Insert BUFFER into the current buffer and quote it."
2085   (interactive "bYank buffer: ")
2086   (let ((message-reply-buffer buffer))
2087     (save-window-excursion
2088       (message-yank-original))))
2089
2090 (defun message-buffers ()
2091   "Return a list of active message buffers."
2092   (let (buffers)
2093     (save-excursion
2094       (dolist (buffer (buffer-list t))
2095         (set-buffer buffer)
2096         (when (and (eq major-mode 'message-mode)
2097                    (null message-sent-message-via))
2098           (push (buffer-name buffer) buffers))))
2099     (nreverse buffers)))
2100
2101 (defun message-cite-original-without-signature ()
2102   "Cite function in the standard Message manner."
2103   (let ((start (point))
2104         (end (mark t))
2105         (functions
2106          (when message-indent-citation-function
2107            (if (listp message-indent-citation-function)
2108                message-indent-citation-function
2109              (list message-indent-citation-function)))))
2110     (mml-quote-region start end)
2111     ;; Allow undoing.
2112     (undo-boundary)
2113     (goto-char end)
2114     (when (re-search-backward message-signature-separator start t)
2115       ;; Also peel off any blank lines before the signature.
2116       (forward-line -1)
2117       (while (looking-at "^[ \t]*$")
2118         (forward-line -1))
2119       (forward-line 1)
2120       (delete-region (point) end))
2121     (goto-char start)
2122     (while functions
2123       (funcall (pop functions)))
2124     (when message-citation-line-function
2125       (unless (bolp)
2126         (insert "\n"))
2127       (funcall message-citation-line-function))))
2128
2129 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
2130 (defun message-cite-original ()
2131   "Cite function in the standard Message manner."
2132   (if (and (boundp 'mail-citation-hook)
2133            mail-citation-hook)
2134       (run-hooks 'mail-citation-hook)
2135     (let ((start (point))
2136           (end (mark t))
2137           (functions
2138            (when message-indent-citation-function
2139              (if (listp message-indent-citation-function)
2140                  message-indent-citation-function
2141                (list message-indent-citation-function)))))
2142       (mml-quote-region start end)
2143       (goto-char start)
2144       (while functions
2145         (funcall (pop functions)))
2146       (when message-citation-line-function
2147         (unless (bolp)
2148           (insert "\n"))
2149         (funcall message-citation-line-function)))))
2150
2151 (defun message-insert-citation-line ()
2152   "Insert a simple citation line."
2153   (when message-reply-headers
2154     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2155
2156 (defun message-position-on-field (header &rest afters)
2157   (let ((case-fold-search t))
2158     (save-restriction
2159       (narrow-to-region
2160        (goto-char (point-min))
2161        (progn
2162          (re-search-forward
2163           (concat "^" (regexp-quote mail-header-separator) "$"))
2164          (match-beginning 0)))
2165       (goto-char (point-min))
2166       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2167           (progn
2168             (re-search-forward "^[^ \t]" nil 'move)
2169             (beginning-of-line)
2170             (skip-chars-backward "\n")
2171             t)
2172         (while (and afters
2173                     (not (re-search-forward
2174                           (concat "^" (regexp-quote (car afters)) ":")
2175                           nil t)))
2176           (pop afters))
2177         (when afters
2178           (re-search-forward "^[^ \t]" nil 'move)
2179           (beginning-of-line))
2180         (insert header ": \n")
2181         (forward-char -1)
2182         nil))))
2183
2184 (defun message-remove-signature ()
2185   "Remove the signature from the text between point and mark.
2186 The text will also be indented the normal way."
2187   (save-excursion
2188     (let ((start (point))
2189           mark)
2190       (if (not (re-search-forward message-signature-separator (mark t) t))
2191           ;; No signature here, so we just indent the cited text.
2192           (message-indent-citation)
2193         ;; Find the last non-empty line.
2194         (forward-line -1)
2195         (while (looking-at "[ \t]*$")
2196           (forward-line -1))
2197         (forward-line 1)
2198         (setq mark (set-marker (make-marker) (point)))
2199         (goto-char start)
2200         (message-indent-citation)
2201         ;; Enable undoing the deletion.
2202         (undo-boundary)
2203         (delete-region mark (mark t))
2204         (set-marker mark nil)))))
2205
2206 \f
2207
2208 ;;;
2209 ;;; Sending messages
2210 ;;;
2211
2212 (defun message-send-and-exit (&optional arg)
2213   "Send message like `message-send', then, if no errors, exit from mail buffer."
2214   (interactive "P")
2215   (let ((buf (current-buffer))
2216         (actions message-exit-actions))
2217     (when (and (message-send arg)
2218                (buffer-name buf))
2219       (if message-kill-buffer-on-exit
2220           (kill-buffer buf)
2221         (bury-buffer buf)
2222         (when (eq buf (current-buffer))
2223           (message-bury buf)))
2224       (message-do-actions actions)
2225       t)))
2226
2227 (defun message-dont-send ()
2228   "Don't send the message you have been editing."
2229   (interactive)
2230   (set-buffer-modified-p t)
2231   (save-buffer)
2232   (let ((actions message-postpone-actions))
2233     (message-bury (current-buffer))
2234     (message-do-actions actions)))
2235
2236 (defun message-kill-buffer ()
2237   "Kill the current buffer."
2238   (interactive)
2239   (when (or (not (buffer-modified-p))
2240             (yes-or-no-p "Message modified; kill anyway? "))
2241     (let ((actions message-kill-actions))
2242       (setq buffer-file-name nil)
2243       (kill-buffer (current-buffer))
2244       (message-do-actions actions))))
2245
2246 (defun message-bury (buffer)
2247   "Bury this mail BUFFER."
2248   (let ((newbuf (other-buffer buffer)))
2249     (bury-buffer buffer)
2250     (if (and (fboundp 'frame-parameters)
2251              (cdr (assq 'dedicated (frame-parameters)))
2252              (not (null (delq (selected-frame) (visible-frame-list)))))
2253         (delete-frame (selected-frame))
2254       (switch-to-buffer newbuf))))
2255
2256 (defun message-send (&optional arg)
2257   "Send the message in the current buffer.
2258 If `message-interactive' is non-nil, wait for success indication or
2259 error messages, and inform user.
2260 Otherwise any failure is reported in a message back to the user from
2261 the mailer.
2262 The usage of ARG is defined by the instance that called Message.
2263 It should typically alter the sending method in some way or other."
2264   (interactive "P")
2265   ;; Make it possible to undo the coming changes.
2266   (undo-boundary)
2267   (let ((inhibit-read-only t))
2268     (put-text-property (point-min) (point-max) 'read-only nil))
2269   (message-fix-before-sending)
2270   (run-hooks 'message-send-hook)
2271   (message message-sending-message)
2272   (let ((alist message-send-method-alist)
2273         (success t)
2274         elem sent
2275         (message-options message-options))
2276     (message-options-set-recipient)
2277     (while (and success
2278                 (setq elem (pop alist)))
2279       (when (funcall (cadr elem))
2280         (when (and (or (not (memq (car elem)
2281                                   message-sent-message-via))
2282                        (if (or (message-gnksa-enable-p 'multiple-copies)
2283                                (not (eq (car elem) 'news)))
2284                            (y-or-n-p
2285                             (format
2286                              "Already sent message via %s; resend? "
2287                              (car elem)))
2288                          (error "Denied posting -- multiple copies.")))
2289                    (setq success (funcall (caddr elem) arg)))
2290           (setq sent t))))
2291     (unless (or sent (not success))
2292       (error "No methods specified to send by"))
2293     (when (and success sent)
2294       (message-do-fcc)
2295       (save-excursion
2296         (run-hooks 'message-sent-hook))
2297       (message "Sending...done")
2298       ;; Mark the buffer as unmodified and delete auto-save.
2299       (set-buffer-modified-p nil)
2300       (delete-auto-save-file-if-necessary t)
2301       (message-disassociate-draft)
2302       ;; Delete other mail buffers and stuff.
2303       (message-do-send-housekeeping)
2304       (message-do-actions message-send-actions)
2305       ;; Return success.
2306       t)))
2307
2308 (defun message-send-via-mail (arg)
2309   "Send the current message via mail."
2310   (message-send-mail arg))
2311
2312 (defun message-send-via-news (arg)
2313   "Send the current message via news."
2314   (funcall message-send-news-function arg))
2315
2316 (defmacro message-check (type &rest forms)
2317   "Eval FORMS if TYPE is to be checked."
2318   `(or (message-check-element ,type)
2319        (save-excursion
2320          ,@forms)))
2321
2322 (put 'message-check 'lisp-indent-function 1)
2323 (put 'message-check 'edebug-form-spec '(form body))
2324
2325 (defun message-fix-before-sending ()
2326   "Do various things to make the message nice before sending it."
2327   ;; Make sure there's a newline at the end of the message.
2328   (goto-char (point-max))
2329   (unless (bolp)
2330     (insert "\n"))
2331   ;; Delete all invisible text.
2332   (message-check 'invisible-text
2333     (when (text-property-any (point-min) (point-max) 'invisible t)
2334       (put-text-property (point-min) (point-max) 'invisible nil)
2335       (unless (yes-or-no-p
2336                "Invisible text found and made visible; continue posting? ")
2337         (error "Invisible text found and made visible")))))
2338
2339 (defun message-add-action (action &rest types)
2340   "Add ACTION to be performed when doing an exit of type TYPES."
2341   (let (var)
2342     (while types
2343       (set (setq var (intern (format "message-%s-actions" (pop types))))
2344            (nconc (symbol-value var) (list action))))))
2345
2346 (defun message-do-actions (actions)
2347   "Perform all actions in ACTIONS."
2348   ;; Now perform actions on successful sending.
2349   (while actions
2350     (ignore-errors
2351       (cond
2352        ;; A simple function.
2353        ((message-functionp (car actions))
2354         (funcall (car actions)))
2355        ;; Something to be evaled.
2356        (t
2357         (eval (car actions)))))
2358     (pop actions)))
2359
2360 (defun message-send-mail-partially ()
2361   "Sendmail as message/partial."
2362   ;; replace the header delimiter with a blank line
2363   (goto-char (point-min))
2364   (re-search-forward
2365    (concat "^" (regexp-quote mail-header-separator) "\n"))
2366   (replace-match "\n")
2367   (run-hooks 'message-send-mail-hook)
2368   (let ((p (goto-char (point-min)))
2369         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2370         (curbuf (current-buffer))
2371         (id (message-make-message-id)) (n 1)
2372         plist total  header required-mail-headers)
2373     (while (not (eobp))
2374       (if (< (point-max) (+ p message-send-mail-partially-limit))
2375           (goto-char (point-max))
2376         (goto-char (+ p message-send-mail-partially-limit))
2377         (beginning-of-line)
2378         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2379       (push p plist)
2380       (setq p (point)))
2381     (setq total (length plist))
2382     (push (point-max) plist)
2383     (setq plist (nreverse plist))
2384     (unwind-protect
2385         (save-excursion
2386           (setq p (pop plist))
2387           (while plist
2388             (set-buffer curbuf)
2389             (copy-to-buffer tembuf p (car plist))
2390             (set-buffer tembuf)
2391             (goto-char (point-min))
2392             (if header
2393                 (progn
2394                   (goto-char (point-min))
2395                   (narrow-to-region (point) (point))
2396                   (insert header))
2397               (message-goto-eoh)
2398               (setq header (buffer-substring (point-min) (point)))
2399               (goto-char (point-min))
2400               (narrow-to-region (point) (point))
2401               (insert header)
2402               (message-remove-header "Mime-Version")
2403               (message-remove-header "Content-Type")
2404               (message-remove-header "Content-Transfer-Encoding")
2405               (message-remove-header "Message-ID")
2406               (message-remove-header "Lines")
2407               (goto-char (point-max))
2408               (insert "Mime-Version: 1.0\n")
2409               (setq header (buffer-substring (point-min) (point-max))))
2410             (goto-char (point-max))
2411             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n"
2412                             id n total))
2413             (let ((mail-header-separator ""))
2414               (when (memq 'Message-ID message-required-mail-headers)
2415                 (insert "Message-ID: " (message-make-message-id) "\n"))
2416               (when (memq 'Lines message-required-mail-headers)
2417                 (let ((mail-header-separator ""))
2418                   (insert "Lines: " (message-make-lines) "\n")))
2419               (message-goto-subject)
2420               (end-of-line)
2421               (insert (format " (%d/%d)" n total))
2422               (goto-char (point-max))
2423               (insert "\n")
2424               (widen)
2425               (mm-with-unibyte-current-buffer
2426                 (funcall message-send-mail-function)))
2427             (setq n (+ n 1))
2428             (setq p (pop plist))
2429             (erase-buffer)))
2430       (kill-buffer tembuf))))
2431
2432 (defun message-send-mail (&optional arg)
2433   (require 'mail-utils)
2434   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2435          (case-fold-search nil)
2436          (news (message-news-p))
2437          (mailbuf (current-buffer))
2438          (message-this-is-mail t)
2439          (message-posting-charset
2440           (if (fboundp 'gnus-setup-posting-charset)
2441               (gnus-setup-posting-charset nil)
2442             message-posting-charset)))
2443     (save-restriction
2444       (message-narrow-to-headers)
2445       ;; Insert some headers.
2446       (let ((message-deletable-headers
2447              (if news nil message-deletable-headers)))
2448         (message-generate-headers message-required-mail-headers))
2449       ;; Let the user do all of the above.
2450       (run-hooks 'message-header-hook))
2451     (unwind-protect
2452         (save-excursion
2453           (set-buffer tembuf)
2454           (erase-buffer)
2455           ;; Avoid copying text props.
2456           (insert (with-current-buffer mailbuf
2457                     (buffer-substring-no-properties (point-min) (point-max))))
2458           ;; Remove some headers.
2459           (message-encode-message-body)
2460           (save-restriction
2461             (message-narrow-to-headers)
2462             ;; We (re)generate the Lines header.
2463             (when (memq 'Lines message-required-mail-headers)
2464               (message-generate-headers '(Lines)))
2465             ;; Remove some headers.
2466             (message-remove-header message-ignored-mail-headers t)
2467             (let ((mail-parse-charset message-default-charset))
2468               (mail-encode-encoded-word-buffer)))
2469           (goto-char (point-max))
2470           ;; require one newline at the end.
2471           (or (= (preceding-char) ?\n)
2472               (insert ?\n))
2473           (when
2474               (save-restriction
2475                 (message-narrow-to-headers)
2476                 (and news
2477                      (or (message-fetch-field "cc")
2478                          (message-fetch-field "to"))
2479                      (string= "text/plain"
2480                               (car
2481                                (mail-header-parse-content-type
2482                                 (message-fetch-field "content-type"))))))
2483             (message-insert-courtesy-copy))
2484           (if (or (not message-send-mail-partially-limit)
2485                   (< (point-max) message-send-mail-partially-limit)
2486                   (not (y-or-n-p "The message size is too large, should it be sent partially? ")))
2487               (mm-with-unibyte-current-buffer
2488                 (funcall message-send-mail-function))
2489             (message-send-mail-partially)))
2490       (kill-buffer tembuf))
2491     (set-buffer mailbuf)
2492     (push 'mail message-sent-message-via)))
2493
2494 (defun message-send-mail-with-sendmail ()
2495   "Send off the prepared buffer with sendmail."
2496   (let ((errbuf (if message-interactive
2497                     (message-generate-new-buffer-clone-locals
2498                      " sendmail errors")
2499                   0))
2500         resend-to-addresses delimline)
2501     (let ((case-fold-search t))
2502       (save-restriction
2503         (message-narrow-to-headers)
2504         (setq resend-to-addresses (message-fetch-field "resent-to")))
2505       ;; Change header-delimiter to be what sendmail expects.
2506       (goto-char (point-min))
2507       (re-search-forward
2508        (concat "^" (regexp-quote mail-header-separator) "\n"))
2509       (replace-match "\n")
2510       (backward-char 1)
2511       (setq delimline (point-marker))
2512       (run-hooks 'message-send-mail-hook)
2513       ;; Insert an extra newline if we need it to work around
2514       ;; Sun's bug that swallows newlines.
2515       (goto-char (1+ delimline))
2516       (when (eval message-mailer-swallows-blank-line)
2517         (newline))
2518       (when message-interactive
2519         (save-excursion
2520           (set-buffer errbuf)
2521           (erase-buffer))))
2522     (let ((default-directory "/")
2523           (coding-system-for-write message-send-coding-system))
2524       (apply 'call-process-region
2525              (append (list (point-min) (point-max)
2526                            (if (boundp 'sendmail-program)
2527                                sendmail-program
2528                              "/usr/lib/sendmail")
2529                            nil errbuf nil "-oi")
2530                      ;; Always specify who from,
2531                      ;; since some systems have broken sendmails.
2532                      ;; But some systems are more broken with -f, so
2533                      ;; we'll let users override this.
2534                      (if (null message-sendmail-f-is-evil)
2535                          (list "-f" (message-make-address)))
2536                      ;; These mean "report errors by mail"
2537                      ;; and "deliver in background".
2538                      (if (null message-interactive) '("-oem" "-odb"))
2539                      ;; Get the addresses from the message
2540                      ;; unless this is a resend.
2541                      ;; We must not do that for a resend
2542                      ;; because we would find the original addresses.
2543                      ;; For a resend, include the specific addresses.
2544                      (if resend-to-addresses
2545                          (list resend-to-addresses)
2546                        '("-t")))))
2547     (when message-interactive
2548       (save-excursion
2549         (set-buffer errbuf)
2550         (goto-char (point-min))
2551         (while (re-search-forward "\n\n* *" nil t)
2552           (replace-match "; "))
2553         (if (not (zerop (buffer-size)))
2554             (error "Sending...failed to %s"
2555                    (buffer-substring (point-min) (point-max)))))
2556       (when (bufferp errbuf)
2557         (kill-buffer errbuf)))))
2558
2559 (defun message-send-mail-with-qmail ()
2560   "Pass the prepared message buffer to qmail-inject.
2561 Refer to the documentation for the variable `message-send-mail-function'
2562 to find out how to use this."
2563   ;; replace the header delimiter with a blank line
2564   (goto-char (point-min))
2565   (re-search-forward
2566    (concat "^" (regexp-quote mail-header-separator) "\n"))
2567   (replace-match "\n")
2568   (run-hooks 'message-send-mail-hook)
2569   ;; send the message
2570   (case
2571       (let ((coding-system-for-write message-send-coding-system))
2572         (apply
2573          'call-process-region 1 (point-max) message-qmail-inject-program
2574          nil nil nil
2575          ;; qmail-inject's default behaviour is to look for addresses on the
2576          ;; command line; if there're none, it scans the headers.
2577          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2578          ;;
2579          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2580          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2581          ;; message from stdin.
2582          ;;
2583          ;; qmail also has the advantage of not having been raped by
2584          ;; various vendors, so we don't have to allow for that, either --
2585          ;; compare this with message-send-mail-with-sendmail and weep
2586          ;; for sendmail's lost innocence.
2587          ;;
2588          ;; all this is way cool coz it lets us keep the arguments entirely
2589          ;; free for -inject-arguments -- a big win for the user and for us
2590          ;; since we don't have to play that double-guessing game and the user
2591          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2592          message-qmail-inject-args))
2593     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2594     ;; we have to look at the retval instead
2595     (0 nil)
2596     (1   (error "qmail-inject reported permanent failure"))
2597     (111 (error "qmail-inject reported transient failure"))
2598     ;; should never happen
2599     (t   (error "qmail-inject reported unknown failure"))))
2600
2601 (defun message-send-mail-with-mh ()
2602   "Send the prepared message buffer with mh."
2603   (let ((mh-previous-window-config nil)
2604         (name (mh-new-draft-name)))
2605     (setq buffer-file-name name)
2606     ;; MH wants to generate these headers itself.
2607     (when message-mh-deletable-headers
2608       (let ((headers message-mh-deletable-headers))
2609         (while headers
2610           (goto-char (point-min))
2611           (and (re-search-forward
2612                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2613                (message-delete-line))
2614           (pop headers))))
2615     (run-hooks 'message-send-mail-hook)
2616     ;; Pass it on to mh.
2617     (mh-send-letter)))
2618
2619 (defun message-send-news (&optional arg)
2620   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2621          (case-fold-search nil)
2622          (method (if (message-functionp message-post-method)
2623                      (funcall message-post-method arg)
2624                    message-post-method))
2625          (group-name-charset (gnus-group-name-charset method ""))
2626          (rfc2047-header-encoding-alist
2627           (if group-name-charset
2628               (cons (cons "Newsgroups" group-name-charset)
2629                     rfc2047-header-encoding-alist)
2630             rfc2047-header-encoding-alist))
2631          (messbuf (current-buffer))
2632          (message-syntax-checks
2633           (if arg
2634               (cons '(existing-newsgroups . disabled)
2635                     message-syntax-checks)
2636             message-syntax-checks))
2637          (message-this-is-news t)
2638          (message-posting-charset (gnus-setup-posting-charset
2639                                    (save-restriction
2640                                      (message-narrow-to-headers-or-head)
2641                                      (message-fetch-field "Newsgroups"))))
2642          result)
2643     (if (not (message-check-news-body-syntax))
2644         nil
2645       (save-restriction
2646         (message-narrow-to-headers)
2647         ;; Insert some headers.
2648         (message-generate-headers message-required-news-headers)
2649         ;; Let the user do all of the above.
2650         (run-hooks 'message-header-hook))
2651       (if group-name-charset
2652           (setq message-syntax-checks
2653               (cons '(valid-newsgroups . disabled)
2654                     message-syntax-checks)))
2655       (message-cleanup-headers)
2656       (if (not (message-check-news-syntax))
2657           nil
2658         (unwind-protect
2659             (save-excursion
2660               (set-buffer tembuf)
2661               (buffer-disable-undo)
2662               (erase-buffer)
2663               ;; Avoid copying text props.
2664               (insert (with-current-buffer messbuf
2665                         (buffer-substring-no-properties
2666                          (point-min) (point-max))))
2667               (message-encode-message-body)
2668               ;; Remove some headers.
2669               (save-restriction
2670                 (message-narrow-to-headers)
2671                 ;; We (re)generate the Lines header.
2672                 (when (memq 'Lines message-required-mail-headers)
2673                   (message-generate-headers '(Lines)))
2674                 ;; Remove some headers.
2675                 (message-remove-header message-ignored-news-headers t)
2676                 (let ((mail-parse-charset message-default-charset))
2677                   (mail-encode-encoded-word-buffer)))
2678               (goto-char (point-max))
2679               ;; require one newline at the end.
2680               (or (= (preceding-char) ?\n)
2681                   (insert ?\n))
2682               (let ((case-fold-search t))
2683                 ;; Remove the delimiter.
2684                 (goto-char (point-min))
2685                 (re-search-forward
2686                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2687                 (replace-match "\n")
2688                 (backward-char 1))
2689               (run-hooks 'message-send-news-hook)
2690               (gnus-open-server method)
2691               (setq result (let ((mail-header-separator ""))
2692                              (gnus-request-post method))))
2693           (kill-buffer tembuf))
2694         (set-buffer messbuf)
2695         (if result
2696             (push 'news message-sent-message-via)
2697           (message "Couldn't send message via news: %s"
2698                    (nnheader-get-report (car method)))
2699           nil)))))
2700
2701 ;;;
2702 ;;; Header generation & syntax checking.
2703 ;;;
2704
2705 (defun message-check-element (type)
2706   "Return non-nil if this TYPE is not to be checked."
2707   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2708       t
2709     (let ((able (assq type message-syntax-checks)))
2710       (and (consp able)
2711            (eq (cdr able) 'disabled)))))
2712
2713 (defun message-check-news-syntax ()
2714   "Check the syntax of the message."
2715   (save-excursion
2716     (save-restriction
2717       (widen)
2718       ;; We narrow to the headers and check them first.
2719       (save-excursion
2720         (save-restriction
2721           (message-narrow-to-headers)
2722           (message-check-news-header-syntax))))))
2723
2724 (defun message-check-news-header-syntax ()
2725   (and
2726    ;; Check Newsgroups header.
2727    (message-check 'newsgroups
2728      (let ((group (message-fetch-field "newsgroups")))
2729        (or
2730         (and group
2731              (not (string-match "\\`[ \t]*\\'" group)))
2732         (ignore
2733          (message
2734           "The newsgroups field is empty or missing.  Posting is denied.")))))
2735    ;; Check the Subject header.
2736    (message-check 'subject
2737      (let* ((case-fold-search t)
2738             (subject (message-fetch-field "subject")))
2739        (or
2740         (and subject
2741              (not (string-match "\\`[ \t]*\\'" subject)))
2742         (ignore
2743          (message
2744           "The subject field is empty or missing.  Posting is denied.")))))
2745    ;; Check for commands in Subject.
2746    (message-check 'subject-cmsg
2747      (if (string-match "^cmsg " (message-fetch-field "subject"))
2748          (y-or-n-p
2749           "The control code \"cmsg\" is in the subject.  Really post? ")
2750        t))
2751    ;; Check for multiple identical headers.
2752    (message-check 'multiple-headers
2753      (let (found)
2754        (while (and (not found)
2755                    (re-search-forward "^[^ \t:]+: " nil t))
2756          (save-excursion
2757            (or (re-search-forward
2758                 (concat "^"
2759                         (regexp-quote
2760                          (setq found
2761                                (buffer-substring
2762                                 (match-beginning 0) (- (match-end 0) 2))))
2763                         ":")
2764                 nil t)
2765                (setq found nil))))
2766        (if found
2767            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2768          t)))
2769    ;; Check for Version and Sendsys.
2770    (message-check 'sendsys
2771      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2772          (y-or-n-p
2773           (format "The article contains a %s command.  Really post? "
2774                   (buffer-substring (match-beginning 0)
2775                                     (1- (match-end 0)))))
2776        t))
2777    ;; See whether we can shorten Followup-To.
2778    (message-check 'shorten-followup-to
2779      (let ((newsgroups (message-fetch-field "newsgroups"))
2780            (followup-to (message-fetch-field "followup-to"))
2781            to)
2782        (when (and newsgroups
2783                   (string-match "," newsgroups)
2784                   (not followup-to)
2785                   (not
2786                    (zerop
2787                     (length
2788                      (setq to (completing-read
2789                                "Followups to: (default all groups) "
2790                                (mapcar (lambda (g) (list g))
2791                                        (cons "poster"
2792                                              (message-tokenize-header
2793                                               newsgroups)))))))))
2794          (goto-char (point-min))
2795          (insert "Followup-To: " to "\n"))
2796        t))
2797    ;; Check "Shoot me".
2798    (message-check 'shoot
2799      (if (re-search-forward
2800           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2801          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2802        t))
2803    ;; Check for Approved.
2804    (message-check 'approved
2805      (if (re-search-forward "^Approved:" nil t)
2806          (y-or-n-p "The article contains an Approved header.  Really post? ")
2807        t))
2808    ;; Check the Message-ID header.
2809    (message-check 'message-id
2810      (let* ((case-fold-search t)
2811             (message-id (message-fetch-field "message-id" t)))
2812        (or (not message-id)
2813            ;; Is there an @ in the ID?
2814            (and (string-match "@" message-id)
2815                 ;; Is there a dot in the ID?
2816                 (string-match "@[^.]*\\." message-id)
2817                 ;; Does the ID end with a dot?
2818                 (not (string-match "\\.>" message-id)))
2819            (y-or-n-p
2820             (format "The Message-ID looks strange: \"%s\".  Really post? "
2821                     message-id)))))
2822    ;; Check the Newsgroups & Followup-To headers.
2823    (message-check 'existing-newsgroups
2824      (let* ((case-fold-search t)
2825             (newsgroups (message-fetch-field "newsgroups"))
2826             (followup-to (message-fetch-field "followup-to"))
2827             (groups (message-tokenize-header
2828                      (if followup-to
2829                          (concat newsgroups "," followup-to)
2830                        newsgroups)))
2831             (hashtb (and (boundp 'gnus-active-hashtb)
2832                          gnus-active-hashtb))
2833             errors)
2834        (if (or (not hashtb)
2835                (not (boundp 'gnus-read-active-file))
2836                (not gnus-read-active-file)
2837                (eq gnus-read-active-file 'some))
2838            t
2839          (while groups
2840            (when (and (not (boundp (intern (car groups) hashtb)))
2841                       (not (equal (car groups) "poster")))
2842              (push (car groups) errors))
2843            (pop groups))
2844          (if (not errors)
2845              t
2846            (y-or-n-p
2847             (format
2848              "Really post to %s unknown group%s: %s? "
2849              (if (= (length errors) 1) "this" "these")
2850              (if (= (length errors) 1) "" "s")
2851              (mapconcat 'identity errors ", ")))))))
2852    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2853    (message-check 'valid-newsgroups
2854      (let ((case-fold-search t)
2855            (headers '("Newsgroups" "Followup-To"))
2856            header error)
2857        (while (and headers (not error))
2858          (when (setq header (mail-fetch-field (car headers)))
2859            (if (or
2860                 (not
2861                  (string-match
2862                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2863                   header))
2864                 (memq
2865                  nil (mapcar
2866                       (lambda (g)
2867                         (not (string-match "\\.\\'\\|\\.\\." g)))
2868                       (message-tokenize-header header ","))))
2869                (setq error t)))
2870          (unless error
2871            (pop headers)))
2872        (if (not error)
2873            t
2874          (y-or-n-p
2875           (format "The %s header looks odd: \"%s\".  Really post? "
2876                   (car headers) header)))))
2877    (message-check 'repeated-newsgroups
2878      (let ((case-fold-search t)
2879            (headers '("Newsgroups" "Followup-To"))
2880            header error groups group)
2881        (while (and headers
2882                    (not error))
2883          (when (setq header (mail-fetch-field (pop headers)))
2884            (setq groups (message-tokenize-header header ","))
2885            (while (setq group (pop groups))
2886              (when (member group groups)
2887                (setq error group
2888                      groups nil)))))
2889        (if (not error)
2890            t
2891          (y-or-n-p
2892           (format "Group %s is repeated in headers.  Really post? " error)))))
2893    ;; Check the From header.
2894    (message-check 'from
2895      (let* ((case-fold-search t)
2896             (from (message-fetch-field "from"))
2897             ad)
2898        (cond
2899         ((not from)
2900          (message "There is no From line.  Posting is denied.")
2901          nil)
2902         ((or (not (string-match
2903                    "@[^\\.]*\\."
2904                    (setq ad (nth 1 (mail-extract-address-components
2905                                     from))))) ;larsi@ifi
2906              (string-match "\\.\\." ad) ;larsi@ifi..uio
2907              (string-match "@\\." ad)   ;larsi@.ifi.uio
2908              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2909              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2910              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2911          (message
2912           "Denied posting -- the From looks strange: \"%s\"." from)
2913          nil)
2914         (t t))))))
2915
2916 (defun message-check-news-body-syntax ()
2917   (and
2918    ;; Check for long lines.
2919    (message-check 'long-lines
2920      (goto-char (point-min))
2921      (re-search-forward
2922       (concat "^" (regexp-quote mail-header-separator) "$"))
2923      (while (and
2924              (progn
2925                (end-of-line)
2926                (< (current-column) 80))
2927              (zerop (forward-line 1))))
2928      (or (bolp)
2929          (eobp)
2930          (y-or-n-p
2931           "You have lines longer than 79 characters.  Really post? ")))
2932    ;; Check whether the article is empty.
2933    (message-check 'empty
2934      (goto-char (point-min))
2935      (re-search-forward
2936       (concat "^" (regexp-quote mail-header-separator) "$"))
2937      (forward-line 1)
2938      (let ((b (point)))
2939        (goto-char (point-max))
2940        (re-search-backward message-signature-separator nil t)
2941        (beginning-of-line)
2942        (or (re-search-backward "[^ \n\t]" b t)
2943            (if (message-gnksa-enable-p 'empty-article)
2944                (y-or-n-p "Empty article.  Really post? ")
2945              (message "Denied posting -- Empty article.")
2946              nil))))
2947    ;; Check for control characters.
2948    (message-check 'control-chars
2949      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2950          (y-or-n-p
2951           "The article contains control characters.  Really post? ")
2952        t))
2953    ;; Check excessive size.
2954    (message-check 'size
2955      (if (> (buffer-size) 60000)
2956          (y-or-n-p
2957           (format "The article is %d octets long.  Really post? "
2958                   (buffer-size)))
2959        t))
2960    ;; Check whether any new text has been added.
2961    (message-check 'new-text
2962      (or
2963       (not message-checksum)
2964       (not (eq (message-checksum) message-checksum))
2965       (if (message-gnksa-enable-p 'quoted-text-only)
2966           (y-or-n-p
2967            "It looks like no new text has been added.  Really post? ")
2968         (message "Denied posting -- no new text has been added.")
2969         nil)))
2970    ;; Check the length of the signature.
2971    (message-check 'signature
2972      (goto-char (point-max))
2973      (if (> (count-lines (point) (point-max)) 5)
2974          (y-or-n-p
2975           (format
2976            "Your .sig is %d lines; it should be max 4.  Really post? "
2977            (1- (count-lines (point) (point-max)))))
2978        t))
2979    ;; Ensure that text follows last quoted portion.
2980    (message-check 'quoting-style
2981      (goto-char (point-max))
2982      (let ((no-problem t))
2983        (when (search-backward-regexp "^>[^\n]*\n" nil t)
2984          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
2985        (if no-problem
2986            t
2987          (if (message-gnksa-enable-p 'quoted-text-only)
2988              (y-or-n-p "Your text should follow quoted text.  Really post? ")
2989            ;; Ensure that
2990            (goto-char (point-min))
2991            (re-search-forward
2992             (concat "^" (regexp-quote mail-header-separator) "$"))
2993            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
2994                (y-or-n-p "Your text should follow quoted text.  Really post? ")
2995              (message "Denied posting -- only quoted text.")
2996              nil)))))))
2997
2998 (defun message-checksum ()
2999   "Return a \"checksum\" for the current buffer."
3000   (let ((sum 0))
3001     (save-excursion
3002       (goto-char (point-min))
3003       (re-search-forward
3004        (concat "^" (regexp-quote mail-header-separator) "$"))
3005       (while (not (eobp))
3006         (when (not (looking-at "[ \t\n]"))
3007           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3008                             (char-after))))
3009         (forward-char 1)))
3010     sum))
3011
3012 (defun message-do-fcc ()
3013   "Process Fcc headers in the current buffer."
3014   (let ((case-fold-search t)
3015         (buf (current-buffer))
3016         list file)
3017     (save-excursion
3018       (set-buffer (get-buffer-create " *message temp*"))
3019       (erase-buffer)
3020       (insert-buffer-substring buf)
3021       (save-restriction
3022         (message-narrow-to-headers)
3023         (while (setq file (message-fetch-field "fcc"))
3024           (push file list)
3025           (message-remove-header "fcc" nil t)))
3026       (message-encode-message-body)
3027       (save-restriction
3028         (message-narrow-to-headers)
3029         (let ((mail-parse-charset message-default-charset)
3030               (rfc2047-header-encoding-alist
3031                (cons '("Newsgroups" . default)
3032                      rfc2047-header-encoding-alist)))
3033           (mail-encode-encoded-word-buffer)))
3034       (goto-char (point-min))
3035       (when (re-search-forward
3036              (concat "^" (regexp-quote mail-header-separator) "$")
3037              nil t)
3038         (replace-match "" t t ))
3039       ;; Process FCC operations.
3040       (while list
3041         (setq file (pop list))
3042         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3043             ;; Pipe the article to the program in question.
3044             (call-process-region (point-min) (point-max) shell-file-name
3045                                  nil nil nil shell-command-switch
3046                                  (match-string 1 file))
3047           ;; Save the article.
3048           (setq file (expand-file-name file))
3049           (unless (file-exists-p (file-name-directory file))
3050             (make-directory (file-name-directory file) t))
3051           (if (and message-fcc-handler-function
3052                    (not (eq message-fcc-handler-function 'rmail-output)))
3053               (funcall message-fcc-handler-function file)
3054             (if (and (file-readable-p file) (mail-file-babyl-p file))
3055                 (rmail-output file 1 nil t)
3056               (let ((mail-use-rfc822 t))
3057                 (rmail-output file 1 t t))))))
3058       (kill-buffer (current-buffer)))))
3059
3060 (defun message-output (filename)
3061   "Append this article to Unix/babyl mail file FILENAME."
3062   (if (and (file-readable-p filename)
3063            (mail-file-babyl-p filename))
3064       (gnus-output-to-rmail filename t)
3065     (gnus-output-to-mail filename t)))
3066
3067 (defun message-cleanup-headers ()
3068   "Do various automatic cleanups of the headers."
3069   ;; Remove empty lines in the header.
3070   (save-restriction
3071     (message-narrow-to-headers)
3072     ;; Remove blank lines.
3073     (while (re-search-forward "^[ \t]*\n" nil t)
3074       (replace-match "" t t))
3075
3076     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3077     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3078     ;; embedded line breaks.
3079     (goto-char (point-min))
3080     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3081       (save-restriction
3082         (narrow-to-region
3083          (point)
3084          (if (re-search-forward "^[^ \t]" nil t)
3085              (match-beginning 0)
3086            (forward-line 1)
3087            (point)))
3088         (goto-char (point-min))
3089         (while (re-search-forward "\n[ \t]+" nil t)
3090           (replace-match " " t t))      ;No line breaks (too confusing)
3091         (goto-char (point-min))
3092         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3093           (replace-match "," t t))
3094         (goto-char (point-min))
3095         ;; Remove trailing commas.
3096         (when (re-search-forward ",+$" nil t)
3097           (replace-match "" t t))))))
3098
3099 (defun message-make-date (&optional now)
3100   "Make a valid data header.
3101 If NOW, use that time instead."
3102   (let* ((now (or now (current-time)))
3103          (zone (nth 8 (decode-time now)))
3104          (sign "+"))
3105     (when (< zone 0)
3106       (setq sign "-")
3107       (setq zone (- zone)))
3108     (concat
3109      (format-time-string "%d" now)
3110      ;; The month name of the %b spec is locale-specific.  Pfff.
3111      (format " %s "
3112              (capitalize (car (rassoc (nth 4 (decode-time now))
3113                                       parse-time-months))))
3114      (format-time-string "%Y %H:%M:%S " now)
3115      ;; We do all of this because XEmacs doesn't have the %z spec.
3116      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3117
3118 (defun message-make-message-id ()
3119   "Make a unique Message-ID."
3120   (concat "<" (message-unique-id)
3121           (let ((psubject (save-excursion (message-fetch-field "subject")))
3122                 (psupersedes
3123                  (save-excursion (message-fetch-field "supersedes"))))
3124             (if (or
3125                  (and message-reply-headers
3126                       (mail-header-references message-reply-headers)
3127                       (mail-header-subject message-reply-headers)
3128                       psubject
3129                       (not (string=
3130                             (message-strip-subject-re
3131                              (mail-header-subject message-reply-headers))
3132                             (message-strip-subject-re psubject))))
3133                  (and psupersedes
3134                       (string-match "_-_@" psupersedes)))
3135                 "_-_" ""))
3136           "@" (message-make-fqdn) ">"))
3137
3138 (defvar message-unique-id-char nil)
3139
3140 ;; If you ever change this function, make sure the new version
3141 ;; cannot generate IDs that the old version could.
3142 ;; You might for example insert a "." somewhere (not next to another dot
3143 ;; or string boundary), or modify the "fsf" string.
3144 (defun message-unique-id ()
3145   ;; Don't use microseconds from (current-time), they may be unsupported.
3146   ;; Instead we use this randomly inited counter.
3147   (setq message-unique-id-char
3148         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3149            ;; (current-time) returns 16-bit ints,
3150            ;; and 2^16*25 just fits into 4 digits i base 36.
3151            (* 25 25)))
3152   (let ((tm (current-time)))
3153     (concat
3154      (if (memq system-type '(ms-dos emx vax-vms))
3155          (let ((user (downcase (user-login-name))))
3156            (while (string-match "[^a-z0-9_]" user)
3157              (aset user (match-beginning 0) ?_))
3158            user)
3159        (message-number-base36 (user-uid) -1))
3160      (message-number-base36 (+ (car   tm)
3161                                (lsh (% message-unique-id-char 25) 16)) 4)
3162      (message-number-base36 (+ (nth 1 tm)
3163                                (lsh (/ message-unique-id-char 25) 16)) 4)
3164      ;; Append the newsreader name, because while the generated
3165      ;; ID is unique to this newsreader, other newsreaders might
3166      ;; otherwise generate the same ID via another algorithm.
3167      ".fsf")))
3168
3169 (defun message-number-base36 (num len)
3170   (if (if (< len 0)
3171           (<= num 0)
3172         (= len 0))
3173       ""
3174     (concat (message-number-base36 (/ num 36) (1- len))
3175             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3176                                   (% num 36))))))
3177
3178 (defun message-make-organization ()
3179   "Make an Organization header."
3180   (let* ((organization
3181           (when message-user-organization
3182             (if (message-functionp message-user-organization)
3183                 (funcall message-user-organization)
3184               message-user-organization))))
3185     (save-excursion
3186       (message-set-work-buffer)
3187       (cond ((stringp organization)
3188              (insert organization))
3189             ((and (eq t organization)
3190                   message-user-organization-file
3191                   (file-exists-p message-user-organization-file))
3192              (insert-file-contents message-user-organization-file)))
3193       (goto-char (point-min))
3194       (while (re-search-forward "[\t\n]+" nil t)
3195         (replace-match "" t t))
3196       (unless (zerop (buffer-size))
3197         (buffer-string)))))
3198
3199 (defun message-make-lines ()
3200   "Count the number of lines and return numeric string."
3201   (save-excursion
3202     (save-restriction
3203       (widen)
3204       (message-goto-body)
3205       (int-to-string (count-lines (point) (point-max))))))
3206
3207 (defun message-make-in-reply-to ()
3208   "Return the In-Reply-To header for this message."
3209   (when message-reply-headers
3210     (let ((from (mail-header-from message-reply-headers))
3211           (date (mail-header-date message-reply-headers))
3212           (msg-id (mail-header-message-id message-reply-headers)))
3213       (when from
3214         (let ((stop-pos
3215                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3216           (concat msg-id (if msg-id " (")
3217                   (if (and stop-pos
3218                            (not (zerop stop-pos)))
3219                       (substring from 0 stop-pos) from)
3220                   "'s message of \""
3221                   (if (or (not date) (string= date ""))
3222                       "(unknown date)" date)
3223                   "\"" (if msg-id ")")))))))
3224
3225 (defun message-make-distribution ()
3226   "Make a Distribution header."
3227   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3228     (cond ((message-functionp message-distribution-function)
3229            (funcall message-distribution-function))
3230           (t orig-distribution))))
3231
3232 (defun message-make-expires ()
3233   "Return an Expires header based on `message-expires'."
3234   (let ((current (current-time))
3235         (future (* 1.0 message-expires 60 60 24)))
3236     ;; Add the future to current.
3237     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3238     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3239     (message-make-date current)))
3240
3241 (defun message-make-path ()
3242   "Return uucp path."
3243   (let ((login-name (user-login-name)))
3244     (cond ((null message-user-path)
3245            (concat (system-name) "!" login-name))
3246           ((stringp message-user-path)
3247            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3248            (concat message-user-path "!" login-name))
3249           (t login-name))))
3250
3251 (defun message-make-from ()
3252   "Make a From header."
3253   (let* ((style message-from-style)
3254          (login (message-make-address))
3255          (fullname
3256           (or (and (boundp 'user-full-name)
3257                    user-full-name)
3258               (user-full-name))))
3259     (when (string= fullname "&")
3260       (setq fullname (user-login-name)))
3261     (save-excursion
3262       (message-set-work-buffer)
3263       (cond
3264        ((or (null style)
3265             (equal fullname ""))
3266         (insert login))
3267        ((or (eq style 'angles)
3268             (and (not (eq style 'parens))
3269                  ;; Use angles if no quoting is needed, or if parens would
3270                  ;; need quoting too.
3271                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3272                      (let ((tmp (concat fullname nil)))
3273                        (while (string-match "([^()]*)" tmp)
3274                          (aset tmp (match-beginning 0) ?-)
3275                          (aset tmp (1- (match-end 0)) ?-))
3276                        (string-match "[\\()]" tmp)))))
3277         (insert fullname)
3278         (goto-char (point-min))
3279         ;; Look for a character that cannot appear unquoted
3280         ;; according to RFC 822.
3281         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3282           ;; Quote fullname, escaping specials.
3283           (goto-char (point-min))
3284           (insert "\"")
3285           (while (re-search-forward "[\"\\]" nil 1)
3286             (replace-match "\\\\\\&" t))
3287           (insert "\""))
3288         (insert " <" login ">"))
3289        (t                               ; 'parens or default
3290         (insert login " (")
3291         (let ((fullname-start (point)))
3292           (insert fullname)
3293           (goto-char fullname-start)
3294           ;; RFC 822 says \ and nonmatching parentheses
3295           ;; must be escaped in comments.
3296           ;; Escape every instance of ()\ ...
3297           (while (re-search-forward "[()\\]" nil 1)
3298             (replace-match "\\\\\\&" t))
3299           ;; ... then undo escaping of matching parentheses,
3300           ;; including matching nested parentheses.
3301           (goto-char fullname-start)
3302           (while (re-search-forward
3303                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3304                   nil 1)
3305             (replace-match "\\1(\\3)" t)
3306             (goto-char fullname-start)))
3307         (insert ")")))
3308       (buffer-string))))
3309
3310 (defun message-make-sender ()
3311   "Return the \"real\" user address.
3312 This function tries to ignore all user modifications, and
3313 give as trustworthy answer as possible."
3314   (concat (user-login-name) "@" (system-name)))
3315
3316 (defun message-make-address ()
3317   "Make the address of the user."
3318   (or (message-user-mail-address)
3319       (concat (user-login-name) "@" (message-make-domain))))
3320
3321 (defun message-user-mail-address ()
3322   "Return the pertinent part of `user-mail-address'."
3323   (when user-mail-address
3324     (if (string-match " " user-mail-address)
3325         (nth 1 (mail-extract-address-components user-mail-address))
3326       user-mail-address)))
3327
3328 (defun message-make-fqdn ()
3329   "Return user's fully qualified domain name."
3330   (let ((system-name (system-name))
3331         (user-mail (message-user-mail-address)))
3332     (cond
3333      ((string-match "[^.]\\.[^.]" system-name)
3334       ;; `system-name' returned the right result.
3335       system-name)
3336      ;; Try `mail-host-address'.
3337      ((and (boundp 'mail-host-address)
3338            (stringp mail-host-address)
3339            (string-match "\\." mail-host-address))
3340       mail-host-address)
3341      ;; We try `user-mail-address' as a backup.
3342      ((and user-mail
3343            (string-match "\\." user-mail)
3344            (string-match "@\\(.*\\)\\'" user-mail))
3345       (match-string 1 user-mail))
3346      ;; Default to this bogus thing.
3347      (t
3348       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3349
3350 (defun message-make-host-name ()
3351   "Return the name of the host."
3352   (let ((fqdn (message-make-fqdn)))
3353     (string-match "^[^.]+\\." fqdn)
3354     (substring fqdn 0 (1- (match-end 0)))))
3355
3356 (defun message-make-domain ()
3357   "Return the domain name."
3358   (or mail-host-address
3359       (message-make-fqdn)))
3360
3361 (defun message-generate-headers (headers)
3362   "Prepare article HEADERS.
3363 Headers already prepared in the buffer are not modified."
3364   (save-restriction
3365     (message-narrow-to-headers)
3366     (let* ((Date (message-make-date))
3367            (Message-ID (message-make-message-id))
3368            (Organization (message-make-organization))
3369            (From (message-make-from))
3370            (Path (message-make-path))
3371            (Subject nil)
3372            (Newsgroups nil)
3373            (In-Reply-To (message-make-in-reply-to))
3374            (To nil)
3375            (Distribution (message-make-distribution))
3376            (Lines (message-make-lines))
3377            (User-Agent message-newsreader)
3378            (Expires (message-make-expires))
3379            (case-fold-search t)
3380            header value elem)
3381       ;; First we remove any old generated headers.
3382       (let ((headers message-deletable-headers))
3383         (unless (buffer-modified-p)
3384           (setq headers (delq 'Message-ID (copy-sequence headers))))
3385         (while headers
3386           (goto-char (point-min))
3387           (and (re-search-forward
3388                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3389                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3390                (message-delete-line))
3391           (pop headers)))
3392       ;; Go through all the required headers and see if they are in the
3393       ;; articles already.  If they are not, or are empty, they are
3394       ;; inserted automatically - except for Subject, Newsgroups and
3395       ;; Distribution.
3396       (while headers
3397         (goto-char (point-min))
3398         (setq elem (pop headers))
3399         (if (consp elem)
3400             (if (eq (car elem) 'optional)
3401                 (setq header (cdr elem))
3402               (setq header (car elem)))
3403           (setq header elem))
3404         (when (or (not (re-search-forward
3405                         (concat "^"
3406                                 (regexp-quote
3407                                  (downcase
3408                                   (if (stringp header)
3409                                       header
3410                                     (symbol-name header))))
3411                                 ":")
3412                         nil t))
3413                   (progn
3414                     ;; The header was found.  We insert a space after the
3415                     ;; colon, if there is none.
3416                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3417                     ;; Find out whether the header is empty...
3418                     (looking-at "[ \t]*\n[^ \t]")))
3419           ;; So we find out what value we should insert.
3420           (setq value
3421                 (cond
3422                  ((and (consp elem) (eq (car elem) 'optional))
3423                   ;; This is an optional header.  If the cdr of this
3424                   ;; is something that is nil, then we do not insert
3425                   ;; this header.
3426                   (setq header (cdr elem))
3427                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3428                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3429                  ((consp elem)
3430                   ;; The element is a cons.  Either the cdr is a
3431                   ;; string to be inserted verbatim, or it is a
3432                   ;; function, and we insert the value returned from
3433                   ;; this function.
3434                   (or (and (stringp (cdr elem)) (cdr elem))
3435                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3436                  ((and (boundp header) (symbol-value header))
3437                   ;; The element is a symbol.  We insert the value
3438                   ;; of this symbol, if any.
3439                   (symbol-value header))
3440                  ((not (message-check-element header))
3441                   ;; We couldn't generate a value for this header,
3442                   ;; so we just ask the user.
3443                   (read-from-minibuffer
3444                    (format "Empty header for %s; enter value: " header)))))
3445           ;; Finally insert the header.
3446           (when (and value
3447                      (not (equal value "")))
3448             (save-excursion
3449               (if (bolp)
3450                   (progn
3451                     ;; This header didn't exist, so we insert it.
3452                     (goto-char (point-max))
3453                     (insert (if (stringp header) header (symbol-name header))
3454                             ": " value "\n")
3455                     (forward-line -1))
3456                 ;; The value of this header was empty, so we clear
3457                 ;; totally and insert the new value.
3458                 (delete-region (point) (gnus-point-at-eol))
3459                 (insert value))
3460               ;; Add the deletable property to the headers that require it.
3461               (and (memq header message-deletable-headers)
3462                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3463                    (add-text-properties
3464                     (point) (match-end 0)
3465                     '(message-deletable t face italic) (current-buffer)))))))
3466       ;; Insert new Sender if the From is strange.
3467       (let ((from (message-fetch-field "from"))
3468             (sender (message-fetch-field "sender"))
3469             (secure-sender (message-make-sender)))
3470         (when (and from
3471                    (not (message-check-element 'sender))
3472                    (not (string=
3473                          (downcase
3474                           (cadr (mail-extract-address-components from)))
3475                          (downcase secure-sender)))
3476                    (or (null sender)
3477                        (not
3478                         (string=
3479                          (downcase
3480                           (cadr (mail-extract-address-components sender)))
3481                          (downcase secure-sender)))))
3482           (goto-char (point-min))
3483           ;; Rename any old Sender headers to Original-Sender.
3484           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3485             (beginning-of-line)
3486             (insert "Original-")
3487             (beginning-of-line))
3488           (when (or (message-news-p)
3489                     (string-match "@.+\\.." secure-sender))
3490             (insert "Sender: " secure-sender "\n")))))))
3491
3492 (defun message-insert-courtesy-copy ()
3493   "Insert a courtesy message in mail copies of combined messages."
3494   (let (newsgroups)
3495     (save-excursion
3496       (save-restriction
3497         (message-narrow-to-headers)
3498         (when (setq newsgroups (message-fetch-field "newsgroups"))
3499           (goto-char (point-max))
3500           (insert "Posted-To: " newsgroups "\n")))
3501       (forward-line 1)
3502       (when message-courtesy-message
3503         (cond
3504          ((string-match "%s" message-courtesy-message)
3505           (insert (format message-courtesy-message newsgroups)))
3506          (t
3507           (insert message-courtesy-message)))))))
3508
3509 ;;;
3510 ;;; Setting up a message buffer
3511 ;;;
3512
3513 (defun message-fill-address (header value)
3514   (save-restriction
3515     (narrow-to-region (point) (point))
3516     (insert (capitalize (symbol-name header))
3517             ": "
3518             (if (consp value) (car value) value)
3519             "\n")
3520     (narrow-to-region (point-min) (1- (point-max)))
3521     (let (quoted last)
3522       (goto-char (point-min))
3523       (while (not (eobp))
3524         (skip-chars-forward "^,\"" (point-max))
3525         (if (or (eq (char-after) ?,)
3526                 (eobp))
3527             (when (not quoted)
3528               (if (and (> (current-column) 78)
3529                        last)
3530                   (progn
3531                     (save-excursion
3532                       (goto-char last)
3533                       (insert "\n\t"))
3534                     (setq last (1+ (point))))
3535                 (setq last (1+ (point)))))
3536           (setq quoted (not quoted)))
3537         (unless (eobp)
3538           (forward-char 1))))
3539     (goto-char (point-max))
3540     (widen)
3541     (forward-line 1)))
3542
3543 (defun message-fill-header (header value)
3544   (let ((begin (point))
3545         (fill-column 78)
3546         (fill-prefix "\t"))
3547     (insert (capitalize (symbol-name header))
3548             ": "
3549             (if (consp value) (car value) value)
3550             "\n")
3551     (save-restriction
3552       (narrow-to-region begin (point))
3553       (fill-region-as-paragraph begin (point))
3554       ;; Tapdance around looong Message-IDs.
3555       (forward-line -1)
3556       (when (looking-at "[ \t]*$")
3557         (message-delete-line))
3558       (goto-char begin)
3559       (re-search-forward ":" nil t)
3560       (when (looking-at "\n[ \t]+")
3561         (replace-match " " t t))
3562       (goto-char (point-max)))))
3563
3564 (defun message-shorten-1 (list cut surplus)
3565   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
3566   (setcdr (nthcdr (- cut 2) list)
3567           (nthcdr (+ (- cut 2) surplus 1) list)))
3568
3569 (defun message-shorten-references (header references)
3570   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
3571 If folding is disallowed, also check that the REFERENCES are less
3572 than 988 characters long, and if they are not, trim them until they are."
3573   (let ((maxcount 31)
3574         (count 0)
3575         (cut 6)
3576         refs)
3577     (with-temp-buffer
3578       (insert references)
3579       (goto-char (point-min))
3580       ;; Cons a list of valid references.
3581       (while (re-search-forward "<[^>]+>" nil t)
3582         (push (match-string 0) refs))
3583       (setq refs (nreverse refs)
3584             count (length refs)))
3585
3586     ;; If the list has more than MAXCOUNT elements, trim it by
3587     ;; removing the CUTth element and the required number of
3588     ;; elements that follow.
3589     (when (> count maxcount)
3590       (let ((surplus (- count maxcount)))
3591         (message-shorten-1 refs cut surplus)
3592         (decf count surplus)))
3593
3594     ;; If folding is disallowed, make sure the total length (including
3595     ;; the spaces between) will be less than MAXSIZE characters.
3596     ;;
3597     ;; Only disallow folding for News messages. At this point the headers
3598     ;; have not been generated, thus we use message-this-is-news directly.
3599     (when (and message-this-is-news message-cater-to-broken-inn)
3600       (let ((maxsize 988)
3601             (totalsize (+ (apply #'+ (mapcar #'length refs))
3602                           (1- count)))
3603             (surplus 0)
3604             (ptr (nthcdr (1- cut) refs)))
3605         ;; Decide how many elements to cut off...
3606         (while (> totalsize maxsize)
3607           (decf totalsize (1+ (length (car ptr))))
3608           (incf surplus)
3609           (setq ptr (cdr ptr)))
3610         ;; ...and do it.
3611         (when (> surplus 0)
3612           (message-shorten-1 refs cut surplus))))
3613
3614     ;; Finally, collect the references back into a string and insert
3615     ;; it into the buffer.
3616     (let ((refstring (mapconcat #'identity refs " ")))
3617       (if (and message-this-is-news message-cater-to-broken-inn)
3618           (insert (capitalize (symbol-name header)) ": "
3619                   refstring "\n")
3620         (message-fill-header header refstring)))))
3621
3622 (defun message-position-point ()
3623   "Move point to where the user probably wants to find it."
3624   (message-narrow-to-headers)
3625   (cond
3626    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3627     (search-backward ":" )
3628     (widen)
3629     (forward-char 1)
3630     (if (eq (char-after) ? )
3631         (forward-char 1)
3632       (insert " ")))
3633    (t
3634     (goto-char (point-max))
3635     (widen)
3636     (forward-line 1)
3637     (unless (looking-at "$")
3638       (forward-line 2)))
3639    (sit-for 0)))
3640
3641 (defun message-buffer-name (type &optional to group)
3642   "Return a new (unique) buffer name based on TYPE and TO."
3643   (cond
3644    ;; Generate a new buffer name The Message Way.
3645    ((eq message-generate-new-buffers 'unique)
3646     (generate-new-buffer-name
3647      (concat "*" type
3648              (if to
3649                  (concat " to "
3650                          (or (car (mail-extract-address-components to))
3651                              to) "")
3652                "")
3653              (if (and group (not (string= group ""))) (concat " on " group) "")
3654              "*")))
3655    ;; Check whether `message-generate-new-buffers' is a function,
3656    ;; and if so, call it.
3657    ((message-functionp message-generate-new-buffers)
3658     (funcall message-generate-new-buffers type to group))
3659    ((eq message-generate-new-buffers 'unsent)
3660     (generate-new-buffer-name
3661      (concat "*unsent " type
3662              (if to
3663                  (concat " to "
3664                          (or (car (mail-extract-address-components to))
3665                              to) "")
3666                "")
3667              (if (and group (not (string= group ""))) (concat " on " group) "")
3668              "*")))
3669    ;; Use standard name.
3670    (t
3671     (format "*%s message*" type))))
3672
3673 (defun message-pop-to-buffer (name)
3674   "Pop to buffer NAME, and warn if it already exists and is modified."
3675   (let ((buffer (get-buffer name)))
3676     (if (and buffer
3677              (buffer-name buffer))
3678         (progn
3679           (set-buffer (pop-to-buffer buffer))
3680           (when (and (buffer-modified-p)
3681                      (not (y-or-n-p
3682                            "Message already being composed; erase? ")))
3683             (error "Message being composed")))
3684       (set-buffer (pop-to-buffer name)))
3685     (erase-buffer)
3686     (message-mode)))
3687
3688 (defun message-do-send-housekeeping ()
3689   "Kill old message buffers."
3690   ;; We might have sent this buffer already.  Delete it from the
3691   ;; list of buffers.
3692   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3693   (while (and message-max-buffers
3694               message-buffer-list
3695               (>= (length message-buffer-list) message-max-buffers))
3696     ;; Kill the oldest buffer -- unless it has been changed.
3697     (let ((buffer (pop message-buffer-list)))
3698       (when (and (buffer-name buffer)
3699                  (not (buffer-modified-p buffer)))
3700         (kill-buffer buffer))))
3701   ;; Rename the buffer.
3702   (if message-send-rename-function
3703       (funcall message-send-rename-function)
3704     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3705       (rename-buffer
3706        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3707   ;; Push the current buffer onto the list.
3708   (when message-max-buffers
3709     (setq message-buffer-list
3710           (nconc message-buffer-list (list (current-buffer))))))
3711
3712 (defun message-mail-user-agent ()
3713   (let ((mua (cond
3714               ((not message-mail-user-agent) nil)
3715               ((eq message-mail-user-agent t) mail-user-agent)
3716               (t message-mail-user-agent))))
3717     (if (memq mua '(message-user-agent gnus-user-agent))
3718         nil
3719       mua)))
3720
3721 (defun message-setup (headers &optional replybuffer actions switch-function)
3722   (let ((mua (message-mail-user-agent))
3723         subject to field yank-action)
3724     (if (not (and message-this-is-mail mua))
3725         (message-setup-1 headers replybuffer actions)
3726       (if replybuffer
3727           (setq yank-action (list 'insert-buffer replybuffer)))
3728       (setq headers (copy-sequence headers))
3729       (setq field (assq 'Subject headers))
3730       (when field
3731         (setq subject (cdr field))
3732         (setq headers (delq field headers)))
3733       (setq field (assq 'To headers))
3734       (when field
3735         (setq to (cdr field))
3736         (setq headers (delq field headers)))
3737       (let ((mail-user-agent mua))
3738         (compose-mail to subject
3739                       (mapcar (lambda (item)
3740                                 (cons
3741                                  (format "%s" (car item))
3742                                  (cdr item)))
3743                               headers)
3744                       nil switch-function yank-action actions)))))
3745
3746 ;;;(defvar mc-modes-alist)
3747 (defun message-setup-1 (headers &optional replybuffer actions)
3748 ;;;   (when (and (boundp 'mc-modes-alist)
3749 ;;;          (not (assq 'message-mode mc-modes-alist)))
3750 ;;;     (push '(message-mode (encrypt . mc-encrypt-message)
3751 ;;;                      (sign . mc-sign-message))
3752 ;;;       mc-modes-alist))
3753   (when actions
3754     (setq message-send-actions actions))
3755   (setq message-reply-buffer replybuffer)
3756   (goto-char (point-min))
3757   ;; Insert all the headers.
3758   (mail-header-format
3759    (let ((h headers)
3760          (alist message-header-format-alist))
3761      (while h
3762        (unless (assq (caar h) message-header-format-alist)
3763          (push (list (caar h)) alist))
3764        (pop h))
3765      alist)
3766    headers)
3767   (delete-region (point) (progn (forward-line -1) (point)))
3768   (when message-default-headers
3769     (insert message-default-headers)
3770     (or (bolp) (insert ?\n)))
3771   (put-text-property
3772    (point)
3773    (progn
3774      (insert mail-header-separator "\n")
3775      (1- (point)))
3776    'read-only nil)
3777   (forward-line -1)
3778   (when (message-news-p)
3779     (when message-default-news-headers
3780       (insert message-default-news-headers)
3781       (or (bolp) (insert ?\n)))
3782     (when message-generate-headers-first
3783       (message-generate-headers
3784        (delq 'Lines
3785              (delq 'Subject
3786                    (copy-sequence message-required-news-headers))))))
3787   (when (message-mail-p)
3788     (when message-default-mail-headers
3789       (insert message-default-mail-headers)
3790       (or (bolp) (insert ?\n)))
3791     (when message-generate-headers-first
3792       (message-generate-headers
3793        (delq 'Lines
3794              (delq 'Subject
3795                    (copy-sequence message-required-mail-headers))))))
3796   (run-hooks 'message-signature-setup-hook)
3797   (message-insert-signature)
3798   (save-restriction
3799     (message-narrow-to-headers)
3800     (if message-alternative-emails
3801         (message-use-alternative-email-as-from))
3802     (run-hooks 'message-header-setup-hook))
3803   (set-buffer-modified-p nil)
3804   (setq buffer-undo-list nil)
3805   (run-hooks 'message-setup-hook)
3806   (message-position-point)
3807   (undo-boundary))
3808
3809 (defun message-set-auto-save-file-name ()
3810   "Associate the message buffer with a file in the drafts directory."
3811   (when message-auto-save-directory
3812     (unless (file-directory-p
3813              (directory-file-name message-auto-save-directory))
3814       (gnus-make-directory message-auto-save-directory))
3815     (if (gnus-alive-p)
3816         (setq message-draft-article
3817               (nndraft-request-associate-buffer "drafts"))
3818       (setq buffer-file-name (expand-file-name "*message*"
3819                                                message-auto-save-directory))
3820       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3821     (clear-visited-file-modtime)
3822     (setq buffer-file-coding-system message-draft-coding-system)))
3823
3824 (defun message-disassociate-draft ()
3825   "Disassociate the message buffer from the drafts directory."
3826   (when message-draft-article
3827     (nndraft-request-expire-articles
3828      (list message-draft-article) "drafts" nil t)))
3829
3830 (defun message-insert-headers ()
3831   "Generate the headers for the article."
3832   (interactive)
3833   (save-excursion
3834     (save-restriction
3835       (message-narrow-to-headers)
3836       (when (message-news-p)
3837         (message-generate-headers
3838          (delq 'Lines
3839                (delq 'Subject
3840                      (copy-sequence message-required-news-headers)))))
3841       (when (message-mail-p)
3842         (message-generate-headers
3843          (delq 'Lines
3844                (delq 'Subject
3845                      (copy-sequence message-required-mail-headers))))))))
3846
3847 \f
3848
3849 ;;;
3850 ;;; Commands for interfacing with message
3851 ;;;
3852
3853 ;;;###autoload
3854 (defun message-mail (&optional to subject
3855                                other-headers continue switch-function
3856                                yank-action send-actions)
3857   "Start editing a mail message to be sent.
3858 OTHER-HEADERS is an alist of header/value pairs."
3859   (interactive)
3860   (let ((message-this-is-mail t) replybuffer)
3861     (unless (message-mail-user-agent)
3862       (message-pop-to-buffer (message-buffer-name "mail" to)))
3863     ;; FIXME: message-mail should do something if YANK-ACTION is not
3864     ;; insert-buffer.
3865     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
3866          (setq replybuffer (nth 1 yank-action)))
3867     (message-setup
3868      (nconc
3869       `((To . ,(or to "")) (Subject . ,(or subject "")))
3870       (when other-headers other-headers))
3871      replybuffer)
3872     ;; FIXME: Should return nil if failure.
3873     t))
3874
3875 ;;;###autoload
3876 (defun message-news (&optional newsgroups subject)
3877   "Start editing a news article to be sent."
3878   (interactive)
3879   (let ((message-this-is-news t))
3880     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3881     (message-setup `((Newsgroups . ,(or newsgroups ""))
3882                      (Subject . ,(or subject ""))))))
3883
3884 (defun message-get-reply-headers (wide &optional to-address)
3885   (let (follow-to mct never-mct from to cc reply-to mrt mft ccalist)
3886     ;; Find all relevant headers we need.
3887     (setq from (message-fetch-field "from")
3888           to (message-fetch-field "to")
3889           cc (message-fetch-field "cc")
3890           mct (message-fetch-field "mail-copies-to")
3891           reply-to (message-fetch-field "reply-to")
3892           mrt (message-fetch-field "mail-reply-to")
3893           mft (message-fetch-field "mail-followup-to"))
3894
3895     ;; Handle special values of Mail-Copies-To.
3896     (when mct
3897       (cond ((or (equal (downcase mct) "never")
3898                  (equal (downcase mct) "nobody"))
3899              (setq never-mct t)
3900              (setq mct nil))
3901             ((or (equal (downcase mct) "always")
3902                  (equal (downcase mct) "poster"))
3903              (setq mct (or mrt reply-to from)))))
3904
3905     (if (or (not wide)
3906             to-address)
3907         (progn
3908           (setq follow-to (list (cons 'To (or to-address mrt reply-to from))))
3909           (when (and wide (or mft mct))
3910             (push (cons 'Cc (or mft mct)) follow-to)))
3911       (let (ccalist)
3912         (save-excursion
3913           (message-set-work-buffer)
3914           (if (and mft
3915                    message-use-followup-to
3916                    (or (not (eq message-use-followup-to 'ask))
3917                        (message-y-or-n-p
3918                         (concat "Obey Mail-Followup-To? ") t "\
3919 You should normally obey the Mail-Followup-To: header.  In this
3920 article, it has the value of
3921
3922 " mft "
3923
3924 which directs your response to " (if (string-match "," mft)
3925                                "the specified addresses"
3926                              "that address only") ".
3927
3928 If a message is posted to several mailing lists, Mail-Followup-To is
3929 often used to direct the following discussion to one list only,
3930 because discussions that are spread over several lists tend to be
3931 fragmented and very difficult to follow.
3932
3933 Also, some source/announcement lists are not indented for discussion;
3934 responses here are directed to other addresses.")))
3935               (insert mft)
3936             (unless never-mct
3937               (insert (or mrt reply-to from "")))
3938             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3939             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3940             (insert (if cc (concat (if (bolp) "" ", ") cc) "")))
3941           (goto-char (point-min))
3942           (while (re-search-forward "[ \t]+" nil t)
3943             (replace-match " " t t))
3944           ;; Remove addresses that match `rmail-dont-reply-to-names'.
3945           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
3946             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3947                       (erase-buffer))))
3948           (goto-char (point-min))
3949           ;; Perhaps "Mail-Copies-To: never" removed the only address?
3950           (when (eobp)
3951             (insert (or mrt reply-to from "")))
3952           (setq ccalist
3953                 (mapcar
3954                  (lambda (addr)
3955                    (cons (mail-strip-quoted-names addr) addr))
3956                  (message-tokenize-header (buffer-string))))
3957           (let ((s ccalist))
3958             (while s
3959               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3960         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3961         (when ccalist
3962           (let ((ccs (cons 'Cc (mapconcat
3963                                 (lambda (addr) (cdr addr)) ccalist ", "))))
3964             (when (string-match "^ +" (cdr ccs))
3965               (setcdr ccs (substring (cdr ccs) (match-end 0))))
3966             (push ccs follow-to)))))
3967     follow-to))
3968
3969
3970 ;;;###autoload
3971 (defun message-reply (&optional to-address wide)
3972   "Start editing a reply to the article in the current buffer."
3973   (interactive)
3974   (require 'gnus-sum)                   ; for gnus-list-identifiers
3975   (let ((cur (current-buffer))
3976         from subject date reply-to to cc
3977         references message-id follow-to
3978         (inhibit-point-motion-hooks t)
3979         (message-this-is-mail t)
3980         gnus-warning)
3981     (save-restriction
3982       (message-narrow-to-head-1)
3983       ;; Allow customizations to have their say.
3984       (if (not wide)
3985           ;; This is a regular reply.
3986           (when (message-functionp message-reply-to-function)
3987             (save-excursion
3988               (setq follow-to (funcall message-reply-to-function))))
3989         ;; This is a followup.
3990         (when (message-functionp message-wide-reply-to-function)
3991           (save-excursion
3992             (setq follow-to
3993                   (funcall message-wide-reply-to-function)))))
3994       (setq message-id (message-fetch-field "message-id" t)
3995             references (message-fetch-field "references")
3996             date (message-fetch-field "date")
3997             from (message-fetch-field "from")
3998             subject (or (message-fetch-field "subject") "none"))
3999     (when gnus-list-identifiers
4000       (setq subject (message-strip-list-identifiers subject)))
4001     (setq subject (concat "Re: " (message-strip-subject-re subject)))
4002
4003     (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4004                (string-match "<[^>]+>" gnus-warning))
4005       (setq message-id (match-string 0 gnus-warning)))
4006
4007     (unless follow-to
4008       (setq follow-to (message-get-reply-headers wide to-address))))
4009
4010     (unless (message-mail-user-agent)
4011       (message-pop-to-buffer
4012        (message-buffer-name
4013         (if wide "wide reply" "reply") from
4014         (if wide to-address nil))))
4015
4016     (setq message-reply-headers
4017           (vector 0 subject from date message-id references 0 0 ""))
4018
4019     (message-setup
4020      `((Subject . ,subject)
4021        ,@follow-to
4022        ,@(if (or references message-id)
4023              `((References . ,(concat (or references "") (and references " ")
4024                                       (or message-id ""))))
4025            nil))
4026      cur)))
4027
4028 ;;;###autoload
4029 (defun message-wide-reply (&optional to-address)
4030   "Make a \"wide\" reply to the message in the current buffer."
4031   (interactive)
4032   (message-reply to-address t))
4033
4034 ;;;###autoload
4035 (defun message-followup (&optional to-newsgroups)
4036   "Follow up to the message in the current buffer.
4037 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4038   (interactive)
4039   (require 'gnus-sum)                   ; for gnus-list-identifiers
4040   (let ((cur (current-buffer))
4041         from subject date reply-to mrt mct
4042         references message-id follow-to
4043         (inhibit-point-motion-hooks t)
4044         (message-this-is-news t)
4045         followup-to distribution newsgroups gnus-warning posted-to)
4046     (save-restriction
4047       (narrow-to-region
4048        (goto-char (point-min))
4049        (if (search-forward "\n\n" nil t)
4050            (1- (point))
4051          (point-max)))
4052       (when (message-functionp message-followup-to-function)
4053         (setq follow-to
4054               (funcall message-followup-to-function)))
4055       (setq from (message-fetch-field "from")
4056             date (message-fetch-field "date")
4057             subject (or (message-fetch-field "subject") "none")
4058             references (message-fetch-field "references")
4059             message-id (message-fetch-field "message-id" t)
4060             followup-to (message-fetch-field "followup-to")
4061             newsgroups (message-fetch-field "newsgroups")
4062             posted-to (message-fetch-field "posted-to")
4063             reply-to (message-fetch-field "reply-to")
4064             mrt (message-fetch-field "mail-reply-to")
4065             distribution (message-fetch-field "distribution")
4066             mct (message-fetch-field "mail-copies-to"))
4067       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4068                  (string-match "<[^>]+>" gnus-warning))
4069         (setq message-id (match-string 0 gnus-warning)))
4070       ;; Remove bogus distribution.
4071       (when (and (stringp distribution)
4072                  (let ((case-fold-search t))
4073                    (string-match "world" distribution)))
4074         (setq distribution nil))
4075       (if gnus-list-identifiers
4076           (setq subject (message-strip-list-identifiers subject)))
4077       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4078       (widen))
4079
4080     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4081
4082     (message-setup
4083      `((Subject . ,subject)
4084        ,@(cond
4085           (to-newsgroups
4086            (list (cons 'Newsgroups to-newsgroups)))
4087           (follow-to follow-to)
4088           ((and followup-to message-use-followup-to)
4089            (list
4090             (cond
4091              ((equal (downcase followup-to) "poster")
4092               (if (or (eq message-use-followup-to 'use)
4093                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
4094 You should normally obey the Followup-To: header.
4095
4096 `Followup-To: poster' sends your response via e-mail instead of news.
4097
4098 A typical situation where `Followup-To: poster' is used is when the poster
4099 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4100                   (progn
4101                     (setq message-this-is-news nil)
4102                     (cons 'To (or mrt reply-to from "")))
4103                 (cons 'Newsgroups newsgroups)))
4104              (t
4105               (if (or (equal followup-to newsgroups)
4106                       (not (eq message-use-followup-to 'ask))
4107                       (message-y-or-n-p
4108                        (concat "Obey Followup-To: " followup-to "? ") t "\
4109 You should normally obey the Followup-To: header.
4110
4111         `Followup-To: " followup-to "'
4112 directs your response to " (if (string-match "," followup-to)
4113                                "the specified newsgroups"
4114                              "that newsgroup only") ".
4115
4116 If a message is posted to several newsgroups, Followup-To is often
4117 used to direct the following discussion to one newsgroup only,
4118 because discussions that are spread over several newsgroup tend to
4119 be fragmented and very difficult to follow.
4120
4121 Also, some source/announcement newsgroups are not indented for discussion;
4122 responses here are directed to other newsgroups."))
4123                   (cons 'Newsgroups followup-to)
4124                 (cons 'Newsgroups newsgroups))))))
4125           (posted-to
4126            `((Newsgroups . ,posted-to)))
4127           (t
4128            `((Newsgroups . ,newsgroups))))
4129        ,@(and distribution (list (cons 'Distribution distribution)))
4130        ,@(if (or references message-id)
4131              `((References . ,(concat (or references "") (and references " ")
4132                                       (or message-id "")))))
4133        ,@(when (and mct
4134                     (not (or (equal (downcase mct) "never")
4135                              (equal (downcase mct) "nobody"))))
4136            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4137                                    (equal (downcase mct) "poster"))
4138                                (or mrt reply-to from "")
4139                              mct)))))
4140
4141      cur)
4142
4143     (setq message-reply-headers
4144           (vector 0 subject from date message-id references 0 0 ""))))
4145
4146
4147 ;;;###autoload
4148 (defun message-cancel-news (&optional arg)
4149   "Cancel an article you posted.
4150 If ARG, allow editing of the cancellation message."
4151   (interactive "P")
4152   (unless (message-news-p)
4153     (error "This is not a news article; canceling is impossible"))
4154   (when (yes-or-no-p "Do you really want to cancel this article? ")
4155     (let (from newsgroups message-id distribution buf sender)
4156       (save-excursion
4157         ;; Get header info from original article.
4158         (save-restriction
4159           (message-narrow-to-head-1)
4160           (setq from (message-fetch-field "from")
4161                 sender (message-fetch-field "sender")
4162                 newsgroups (message-fetch-field "newsgroups")
4163                 message-id (message-fetch-field "message-id" t)
4164                 distribution (message-fetch-field "distribution")))
4165         ;; Make sure that this article was written by the user.
4166         (unless (or (and sender
4167                          (string-equal
4168                           (downcase sender)
4169                           (downcase (message-make-sender))))
4170                     (string-equal
4171                      (downcase (cadr (mail-extract-address-components from)))
4172                      (downcase (cadr (mail-extract-address-components
4173                                       (message-make-from))))))
4174           (error "This article is not yours"))
4175         ;; Make control message.
4176         (if arg
4177             (message-news)
4178           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4179         (erase-buffer)
4180         (insert "Newsgroups: " newsgroups "\n"
4181                "From: " from "\n"
4182                 "Subject: cmsg cancel " message-id "\n"
4183                 "Control: cancel " message-id "\n"
4184                 (if distribution
4185                     (concat "Distribution: " distribution "\n")
4186                   "")
4187                 mail-header-separator "\n"
4188                 message-cancel-message)
4189         (run-hooks 'message-cancel-hook)
4190         (unless arg
4191           (message "Canceling your article...")
4192           (if (let ((message-syntax-checks
4193                      'dont-check-for-anything-just-trust-me))
4194                 (funcall message-send-news-function))
4195               (message "Canceling your article...done"))
4196           (kill-buffer buf))))))
4197
4198 ;;;###autoload
4199 (defun message-supersede ()
4200   "Start composing a message to supersede the current message.
4201 This is done simply by taking the old article and adding a Supersedes
4202 header line with the old Message-ID."
4203   (interactive)
4204   (let ((cur (current-buffer))
4205         (sender (message-fetch-field "sender"))
4206         (from (message-fetch-field "from")))
4207     ;; Check whether the user owns the article that is to be superseded.
4208     (unless (or (and sender
4209                      (string-equal
4210                       (downcase sender)
4211                       (downcase (message-make-sender))))
4212                 (string-equal
4213                  (downcase (cadr (mail-extract-address-components from)))
4214                  (downcase (cadr (mail-extract-address-components
4215                                   (message-make-from))))))
4216       (error "This article is not yours"))
4217     ;; Get a normal message buffer.
4218     (message-pop-to-buffer (message-buffer-name "supersede"))
4219     (insert-buffer-substring cur)
4220     (mime-to-mml)
4221     (message-narrow-to-head-1)
4222     ;; Remove unwanted headers.
4223     (when message-ignored-supersedes-headers
4224       (message-remove-header message-ignored-supersedes-headers t))
4225     (goto-char (point-min))
4226     (if (not (re-search-forward "^Message-ID: " nil t))
4227         (error "No Message-ID in this article")
4228       (replace-match "Supersedes: " t t))
4229     (goto-char (point-max))
4230     (insert mail-header-separator)
4231     (widen)
4232     (forward-line 1)))
4233
4234 ;;;###autoload
4235 (defun message-recover ()
4236   "Reread contents of current buffer from its last auto-save file."
4237   (interactive)
4238   (let ((file-name (make-auto-save-file-name)))
4239     (cond ((save-window-excursion
4240              (if (not (eq system-type 'vax-vms))
4241                  (with-output-to-temp-buffer "*Directory*"
4242                    (with-current-buffer standard-output
4243                      (fundamental-mode)) ; for Emacs 20.4+
4244                    (buffer-disable-undo standard-output)
4245                    (let ((default-directory "/"))
4246                      (call-process
4247                       "ls" nil standard-output nil "-l" file-name))))
4248              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4249            (let ((buffer-read-only nil))
4250              (erase-buffer)
4251              (insert-file-contents file-name nil)))
4252           (t (error "message-recover cancelled")))))
4253
4254 ;;; Washing Subject:
4255
4256 (defun message-wash-subject (subject)
4257   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
4258 Previous forwarders, replyers, etc. may add it."
4259   (with-temp-buffer
4260     (insert-string subject)
4261     (goto-char (point-min))
4262     ;; strip Re/Fwd stuff off the beginning
4263     (while (re-search-forward
4264             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4265       (replace-match ""))
4266
4267     ;; and gnus-style forwards [foo@bar.com] subject
4268     (goto-char (point-min))
4269     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4270       (replace-match ""))
4271
4272     ;; and off the end
4273     (goto-char (point-max))
4274     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4275       (replace-match ""))
4276
4277     ;; and finally, any whitespace that was left-over
4278     (goto-char (point-min))
4279     (while (re-search-forward "^[ \t]+" nil t)
4280       (replace-match ""))
4281     (goto-char (point-max))
4282     (while (re-search-backward "[ \t]+$" nil t)
4283       (replace-match ""))
4284
4285     (buffer-string)))
4286
4287 ;;; Forwarding messages.
4288
4289 (defun message-forward-subject-author-subject (subject)
4290   "Generate a SUBJECT for a forwarded message.
4291 The form is: [Source] Subject, where if the original message was mail,
4292 Source is the sender, and if the original message was news, Source is
4293 the list of newsgroups is was posted to."
4294   (concat "["
4295           (or (message-fetch-field
4296                (if (message-news-p) "newsgroups" "from"))
4297               "(nowhere)")
4298           "] " subject))
4299
4300 (defun message-forward-subject-fwd (subject)
4301   "Generate a SUBJECT for a forwarded message.
4302 The form is: Fwd: Subject, where Subject is the original subject of
4303 the message."
4304   (concat "Fwd: " subject))
4305
4306 (defun message-make-forward-subject ()
4307   "Return a Subject header suitable for the message in the current buffer."
4308   (save-excursion
4309     (save-restriction
4310       (message-narrow-to-head-1)
4311       (let ((funcs message-make-forward-subject-function)
4312             (subject (message-fetch-field "Subject")))
4313         (setq subject
4314               (if subject
4315                   (mail-decode-encoded-word-string subject)
4316                 ""))
4317         (if message-wash-forwarded-subjects
4318             (setq subject (message-wash-subject subject)))
4319         ;; Make sure funcs is a list.
4320         (and funcs
4321              (not (listp funcs))
4322              (setq funcs (list funcs)))
4323         ;; Apply funcs in order, passing subject generated by previous
4324         ;; func to the next one.
4325         (while funcs
4326           (when (message-functionp (car funcs))
4327             (setq subject (funcall (car funcs) subject)))
4328           (setq funcs (cdr funcs)))
4329         subject))))
4330
4331 ;;;###autoload
4332 (defun message-forward (&optional news digest)
4333   "Forward the current message via mail.
4334 Optional NEWS will use news to forward instead of mail.
4335 Optional DIGEST will use digest to forward."
4336   (interactive "P")
4337   (let* ((cur (current-buffer))
4338          (subject (message-make-forward-subject))
4339          art-beg)
4340     (if news
4341         (message-news nil subject)
4342       (message-mail nil subject))
4343     ;; Put point where we want it before inserting the forwarded
4344     ;; message.
4345     (if message-forward-before-signature
4346         (message-goto-body)
4347       (goto-char (point-max)))
4348     (if message-forward-as-mime
4349         (if digest
4350             (insert "\n<#multipart type=digest>\n")
4351           (if message-forward-show-mml
4352               (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4353             (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4354       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4355     (let ((b (point)) e)
4356       (if digest
4357           (if message-forward-as-mime
4358               (insert-buffer-substring cur)
4359             (mml-insert-buffer cur))
4360         (if message-forward-show-mml
4361             (let ((target (current-buffer)) tmp)
4362               (with-temp-buffer
4363                 (mm-disable-multibyte) ;; Must copy buffer in unibyte mode
4364                 (setq tmp (current-buffer))
4365                 (set-buffer cur)
4366                 (mm-with-unibyte-current-buffer
4367                   (set-buffer tmp)
4368                   (insert-buffer-substring cur)
4369                   (set-buffer cur))
4370                 (set-buffer tmp)
4371                 (mm-enable-multibyte)
4372                 (mime-to-mml)
4373                 (goto-char (point-min))
4374                 (when (looking-at "From ")
4375                   (replace-match "X-From-Line: "))
4376                 (set-buffer target)
4377                 (insert-buffer-substring tmp)
4378                 (set-buffer tmp)))
4379           (save-restriction
4380             (narrow-to-region (point) (point))
4381             (mml-insert-buffer cur)
4382             (goto-char (point-min))
4383             (when (looking-at "From ")
4384               (replace-match "X-From-Line: "))
4385             (goto-char (point-max)))))
4386       (setq e (point))
4387       (if message-forward-as-mime
4388           (if digest
4389               (insert "<#/multipart>\n")
4390             (if message-forward-show-mml
4391                 (insert "<#/mml>\n")
4392               (insert "<#/part>\n")))
4393         (insert "\n-------------------- End of forwarded message --------------------\n"))
4394       (if (and digest message-forward-as-mime)
4395           (save-restriction
4396             (narrow-to-region b e)
4397             (goto-char b)
4398             (narrow-to-region (point)
4399                               (or (search-forward "\n\n" nil t) (point)))
4400             (delete-region (point-min) (point-max)))
4401         (when (and (not current-prefix-arg)
4402                    message-forward-ignored-headers)
4403           (save-restriction
4404             (narrow-to-region b e)
4405             (goto-char b)
4406             (narrow-to-region (point)
4407                               (or (search-forward "\n\n" nil t) (point)))
4408             (message-remove-header message-forward-ignored-headers t)))))
4409     (message-position-point)))
4410
4411 ;;;###autoload
4412 (defun message-resend (address)
4413   "Resend the current article to ADDRESS."
4414   (interactive
4415    (list (message-read-from-minibuffer "Resend message to: ")))
4416   (message "Resending message to %s..." address)
4417   (save-excursion
4418     (let ((cur (current-buffer))
4419           beg)
4420       ;; We first set up a normal mail buffer.
4421       (unless (message-mail-user-agent)
4422         (set-buffer (get-buffer-create " *message resend*"))
4423         (erase-buffer))
4424       (let ((message-this-is-mail t))
4425         (message-setup `((To . ,address))))
4426       ;; Insert our usual headers.
4427       (message-generate-headers '(From Date To))
4428       (message-narrow-to-headers)
4429       ;; Rename them all to "Resent-*".
4430       (while (re-search-forward "^[A-Za-z]" nil t)
4431         (forward-char -1)
4432         (insert "Resent-"))
4433       (widen)
4434       (forward-line)
4435       (delete-region (point) (point-max))
4436       (setq beg (point))
4437       ;; Insert the message to be resent.
4438       (insert-buffer-substring cur)
4439       (goto-char (point-min))
4440       (search-forward "\n\n")
4441       (forward-char -1)
4442       (save-restriction
4443         (narrow-to-region beg (point))
4444         (message-remove-header message-ignored-resent-headers t)
4445         (goto-char (point-max)))
4446       (insert mail-header-separator)
4447       ;; Rename all old ("Also-")Resent headers.
4448       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4449         (beginning-of-line)
4450         (insert "Also-"))
4451       ;; Quote any "From " lines at the beginning.
4452       (goto-char beg)
4453       (when (looking-at "From ")
4454         (replace-match "X-From-Line: "))
4455       ;; Send it.
4456       (let ((message-inhibit-body-encoding t)
4457             message-required-mail-headers)
4458         (message-send-mail))
4459       (kill-buffer (current-buffer)))
4460     (message "Resending message to %s...done" address)))
4461
4462 ;;;###autoload
4463 (defun message-bounce ()
4464   "Re-mail the current message.
4465 This only makes sense if the current message is a bounce message that
4466 contains some mail you have written which has been bounced back to
4467 you."
4468   (interactive)
4469   (let ((handles (mm-dissect-buffer t))
4470         boundary)
4471     (message-pop-to-buffer (message-buffer-name "bounce"))
4472     (if (stringp (car handles))
4473         ;; This is a MIME bounce.
4474         (mm-insert-part (car (last handles)))
4475       ;; This is a non-MIME bounce, so we try to remove things
4476       ;; manually.
4477       (mm-insert-part handles)
4478       (undo-boundary)
4479       (goto-char (point-min))
4480       (search-forward "\n\n" nil t)
4481       (or (and (re-search-forward message-unsent-separator nil t)
4482                (forward-line 1))
4483           (re-search-forward "^Return-Path:.*\n" nil t))
4484       ;; We remove everything before the bounced mail.
4485       (delete-region
4486        (point-min)
4487        (if (re-search-forward "^[^ \n\t]+:" nil t)
4488            (match-beginning 0)
4489          (point))))
4490     (mm-enable-multibyte)
4491     (mime-to-mml)
4492     (save-restriction
4493       (message-narrow-to-head-1)
4494       (message-remove-header message-ignored-bounced-headers t)
4495       (goto-char (point-max))
4496       (insert mail-header-separator))
4497     (message-position-point)))
4498
4499 ;;;
4500 ;;; Interactive entry points for new message buffers.
4501 ;;;
4502
4503 ;;;###autoload
4504 (defun message-mail-other-window (&optional to subject)
4505   "Like `message-mail' command, but display mail buffer in another window."
4506   (interactive)
4507   (unless (message-mail-user-agent)
4508     (let ((pop-up-windows t)
4509           (special-display-buffer-names nil)
4510           (special-display-regexps nil)
4511           (same-window-buffer-names nil)
4512           (same-window-regexps nil))
4513       (message-pop-to-buffer (message-buffer-name "mail" to))))
4514   (let ((message-this-is-mail t))
4515     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4516                    nil nil 'switch-to-buffer-other-window)))
4517
4518 ;;;###autoload
4519 (defun message-mail-other-frame (&optional to subject)
4520   "Like `message-mail' command, but display mail buffer in another frame."
4521   (interactive)
4522   (unless (message-mail-user-agent)
4523     (let ((pop-up-frames t)
4524           (special-display-buffer-names nil)
4525           (special-display-regexps nil)
4526           (same-window-buffer-names nil)
4527           (same-window-regexps nil))
4528       (message-pop-to-buffer (message-buffer-name "mail" to))))
4529   (let ((message-this-is-mail t))
4530     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4531                    nil nil 'switch-to-buffer-other-frame)))
4532
4533 ;;;###autoload
4534 (defun message-news-other-window (&optional newsgroups subject)
4535   "Start editing a news article to be sent."
4536   (interactive)
4537   (let ((pop-up-windows t)
4538         (special-display-buffer-names nil)
4539         (special-display-regexps nil)
4540         (same-window-buffer-names nil)
4541         (same-window-regexps nil))
4542     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4543   (let ((message-this-is-news t))
4544     (message-setup `((Newsgroups . ,(or newsgroups ""))
4545                      (Subject . ,(or subject ""))))))
4546
4547 ;;;###autoload
4548 (defun message-news-other-frame (&optional newsgroups subject)
4549   "Start editing a news article to be sent."
4550   (interactive)
4551   (let ((pop-up-frames t)
4552         (special-display-buffer-names nil)
4553         (special-display-regexps nil)
4554         (same-window-buffer-names nil)
4555         (same-window-regexps nil))
4556     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4557   (let ((message-this-is-news t))
4558     (message-setup `((Newsgroups . ,(or newsgroups ""))
4559                      (Subject . ,(or subject ""))))))
4560
4561 ;;; underline.el
4562
4563 ;; This code should be moved to underline.el (from which it is stolen).
4564
4565 ;;;###autoload
4566 (defun bold-region (start end)
4567   "Bold all nonblank characters in the region.
4568 Works by overstriking characters.
4569 Called from program, takes two arguments START and END
4570 which specify the range to operate on."
4571   (interactive "r")
4572   (save-excursion
4573     (let ((end1 (make-marker)))
4574       (move-marker end1 (max start end))
4575       (goto-char (min start end))
4576       (while (< (point) end1)
4577         (or (looking-at "[_\^@- ]")
4578             (insert (char-after) "\b"))
4579         (forward-char 1)))))
4580
4581 ;;;###autoload
4582 (defun unbold-region (start end)
4583   "Remove all boldness (overstruck characters) in the region.
4584 Called from program, takes two arguments START and END
4585 which specify the range to operate on."
4586   (interactive "r")
4587   (save-excursion
4588     (let ((end1 (make-marker)))
4589       (move-marker end1 (max start end))
4590       (goto-char (min start end))
4591       (while (re-search-forward "\b" end1 t)
4592         (if (eq (char-after) (char-after (- (point) 2)))
4593             (delete-char -2))))))
4594
4595 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4596
4597 ;; Support for toolbar
4598 (eval-when-compile 
4599   (defvar tool-bar-map)
4600   (defvar tool-bar-mode))
4601
4602 (defun message-tool-bar-map ()
4603   (or message-tool-bar-map
4604       (setq message-tool-bar-map
4605             (and (fboundp 'tool-bar-add-item-from-menu)
4606                  tool-bar-mode
4607                  (let ((tool-bar-map (copy-keymap tool-bar-map))
4608                        (load-path (mm-image-load-path)))
4609                    ;; Zap some items which aren't so relevant and take
4610                    ;; up space.
4611                    (dolist (key '(print-buffer kill-buffer save-buffer 
4612                                                write-file dired open-file))
4613                      (define-key tool-bar-map (vector key) nil))
4614                    (tool-bar-add-item-from-menu
4615                     'message-send-and-exit "mail_send" message-mode-map)
4616                    (tool-bar-add-item-from-menu
4617                     'message-kill-buffer "close" message-mode-map)
4618                    (tool-bar-add-item-from-menu
4619                     'message-dont-send "cancel" message-mode-map)
4620                    (tool-bar-add-item-from-menu
4621                     'mml-attach-file "attach" message-mode-map)
4622                    (tool-bar-add-item-from-menu
4623                     'ispell-message "spell" message-mode-map)
4624                    tool-bar-map)))))
4625
4626 ;;; Group name completion.
4627
4628 (defvar message-newgroups-header-regexp
4629   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4630   "Regexp that match headers that lists groups.")
4631
4632 (defun message-tab ()
4633   "Expand group names in Newsgroups and Followup-To headers.
4634 Do a `tab-to-tab-stop' if not in those headers."
4635   (interactive)
4636   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4637         (mail-abbrev-in-expansion-header-p))
4638       (message-expand-group)
4639     (tab-to-tab-stop)))
4640
4641 (defun message-expand-group ()
4642   "Expand the group name under point."
4643   (let* ((b (save-excursion
4644               (save-restriction
4645                 (narrow-to-region
4646                  (save-excursion
4647                    (beginning-of-line)
4648                    (skip-chars-forward "^:")
4649                    (1+ (point)))
4650                  (point))
4651                 (skip-chars-backward "^, \t\n") (point))))
4652          (completion-ignore-case t)
4653          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4654                                             (point))))
4655          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4656          (completions (all-completions string hashtb))
4657          comp)
4658     (delete-region b (point))
4659     (cond
4660      ((= (length completions) 1)
4661       (if (string= (car completions) string)
4662           (progn
4663             (insert string)
4664             (message "Only matching group"))
4665         (insert (car completions))))
4666      ((and (setq comp (try-completion string hashtb))
4667            (not (string= comp string)))
4668       (insert comp))
4669      (t
4670       (insert string)
4671       (if (not comp)
4672           (message "No matching groups")
4673         (save-selected-window
4674           (pop-to-buffer "*Completions*")
4675           (buffer-disable-undo)
4676           (let ((buffer-read-only nil))
4677             (erase-buffer)
4678             (let ((standard-output (current-buffer)))
4679               (display-completion-list (sort completions 'string<)))
4680             (goto-char (point-min))
4681             (delete-region (point) (progn (forward-line 3) (point))))))))))
4682
4683 ;;; Help stuff.
4684
4685 (defun message-talkative-question (ask question show &rest text)
4686   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4687 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4688 The following arguments may contain lists of values."
4689   (if (and show
4690            (setq text (message-flatten-list text)))
4691       (save-window-excursion
4692         (save-excursion
4693           (with-output-to-temp-buffer " *MESSAGE information message*"
4694             (set-buffer " *MESSAGE information message*")
4695             (fundamental-mode)          ; for Emacs 20.4+
4696             (mapcar 'princ text)
4697             (goto-char (point-min))))
4698         (funcall ask question))
4699     (funcall ask question)))
4700
4701 (defun message-flatten-list (list)
4702   "Return a new, flat list that contains all elements of LIST.
4703
4704 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4705 => (1 2 3 4 5 6 7)"
4706   (cond ((consp list)
4707          (apply 'append (mapcar 'message-flatten-list list)))
4708         (list
4709          (list list))))
4710
4711 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4712   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
4713 Then clone the local variables and values from the old buffer to the
4714 new one, cloning only the locals having a substring matching the
4715 regexp varstr."
4716   (let ((oldbuf (current-buffer)))
4717     (save-excursion
4718       (set-buffer (generate-new-buffer name))
4719       (message-clone-locals oldbuf varstr)
4720       (current-buffer))))
4721
4722 (defun message-clone-locals (buffer &optional varstr)
4723   "Clone the local variables from BUFFER to the current buffer."
4724   (let ((locals (save-excursion
4725                   (set-buffer buffer)
4726                   (buffer-local-variables)))
4727         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4728     (mapcar
4729      (lambda (local)
4730        (when (and (consp local)
4731                   (car local)
4732                   (string-match regexp (symbol-name (car local)))
4733                   (or (null varstr)
4734                       (string-match varstr (symbol-name (car local)))))
4735          (ignore-errors
4736            (set (make-local-variable (car local))
4737                 (cdr local)))))
4738      locals)))
4739
4740 ;;; Miscellaneous functions
4741
4742 (defsubst message-replace-chars-in-string (string from to)
4743   (mm-subst-char-in-string from to string))
4744
4745 ;;;
4746 ;;; MIME functions
4747 ;;;
4748
4749 (defvar message-inhibit-body-encoding nil)
4750
4751 (defun message-encode-message-body ()
4752   (unless message-inhibit-body-encoding
4753     (let ((mail-parse-charset (or mail-parse-charset
4754                                   message-default-charset))
4755           (case-fold-search t)
4756           lines content-type-p)
4757       (message-goto-body)
4758       (save-restriction
4759         (narrow-to-region (point) (point-max))
4760         (let ((new (mml-generate-mime)))
4761           (when new
4762             (delete-region (point-min) (point-max))
4763             (insert new)
4764             (goto-char (point-min))
4765             (if (eq (aref new 0) ?\n)
4766                 (delete-char 1)
4767               (search-forward "\n\n")
4768               (setq lines (buffer-substring (point-min) (1- (point))))
4769               (delete-region (point-min) (point))))))
4770       (save-restriction
4771         (message-narrow-to-headers-or-head)
4772         (message-remove-header "Mime-Version")
4773         (goto-char (point-max))
4774         (insert "MIME-Version: 1.0\n")
4775         (when lines
4776           (insert lines))
4777         (setq content-type-p
4778               (re-search-backward "^Content-Type:" nil t)))
4779       (save-restriction
4780         (message-narrow-to-headers-or-head)
4781         (message-remove-first-header "Content-Type")
4782         (message-remove-first-header "Content-Transfer-Encoding"))
4783       ;; We always make sure that the message has a Content-Type header.
4784       ;; This is because some broken MTAs and MUAs get awfully confused
4785       ;; when confronted with a message with a MIME-Version header and
4786       ;; without a Content-Type header.  For instance, Solaris'
4787       ;; /usr/bin/mail.
4788       (unless content-type-p
4789         (goto-char (point-min))
4790         (re-search-forward "^MIME-Version:")
4791         (forward-line 1)
4792         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
4793
4794 (defun message-read-from-minibuffer (prompt)
4795   "Read from the minibuffer while providing abbrev expansion."
4796   (if (fboundp 'mail-abbrevs-setup)
4797       (let ((mail-abbrev-mode-regexp "")
4798             (minibuffer-setup-hook 'mail-abbrevs-setup)
4799             (minibuffer-local-map message-minibuffer-local-map))
4800         (read-from-minibuffer prompt))
4801     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
4802           (minibuffer-local-map message-minibuffer-local-map))
4803       (read-string prompt))))
4804
4805 (defun message-use-alternative-email-as-from ()
4806   (require 'mail-utils)
4807   (let* ((fields '("To" "Cc"))
4808          (emails
4809           (split-string
4810            (mail-strip-quoted-names
4811             (mapconcat 'message-fetch-reply-field fields ","))
4812            "[ \f\t\n\r\v,]+"))
4813          email)
4814     (while emails
4815       (if (string-match message-alternative-emails (car emails))
4816           (setq email (car emails)
4817                 emails nil))
4818       (pop emails))
4819     (unless (or (not email) (equal email user-mail-address))
4820       (goto-char (point-max))
4821       (insert "From: " email "\n"))))
4822
4823 (defun message-options-get (symbol)
4824   (cdr (assq symbol message-options)))
4825
4826 (defun message-options-set (symbol value)
4827   (let ((the-cons (assq symbol message-options)))
4828     (if the-cons
4829         (if value 
4830             (setcdr the-cons value)
4831           (setq message-options (delq the-cons message-options)))
4832       (and value
4833            (push (cons symbol value) message-options))))
4834   value)
4835
4836 (defun message-options-set-recipient ()
4837   (save-restriction
4838     (message-narrow-to-headers-or-head)
4839     (message-options-set 'message-sender
4840                          (mail-strip-quoted-names 
4841                           (message-fetch-field "from")))
4842     (message-options-set 'message-recipients
4843                           (mail-strip-quoted-names 
4844                            (message-fetch-field "to")))))
4845
4846 (when (featurep 'xemacs)
4847   (require 'messagexmas)
4848   (message-xmas-redefine))
4849
4850 (provide 'message)
4851
4852 (run-hooks 'message-load-hook)
4853
4854 ;; Local Variables:
4855 ;; coding: iso-8859-1
4856 ;; End:
4857
4858 ;;; message.el ends here