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