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