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