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   (define-key message-mode-map "\C-c\C-p" 'message-insert-or-toggle-importance)
1513
1514   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1515   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1516   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1517   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1518   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1519   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1520   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1521   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1522
1523   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1524   (define-key message-mode-map "\C-c\C-s" 'message-send)
1525   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1526   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1527   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
1528
1529   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1530   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1531   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1532   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1533   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
1534
1535   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1536   
1537   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
1538   (define-key message-mode-map "\t" 'message-tab)
1539   (define-key message-mode-map "\M-;" 'comment-region))
1540
1541 (easy-menu-define
1542   message-mode-menu message-mode-map "Message Menu."
1543   `("Message"
1544     ["Sort Headers" message-sort-headers t]
1545     ["Yank Original" message-yank-original t]
1546     ["Fill Yanked Message" message-fill-yanked-message t]
1547     ["Insert Signature" message-insert-signature t]
1548     ["Caesar (rot13) Message" message-caesar-buffer-body t]
1549     ["Caesar (rot13) Region" message-caesar-region (mark t)]
1550     ["Elide Region" message-elide-region (mark t)]
1551     ["Delete Outside Region" message-delete-not-region (mark t)]
1552     ["Kill To Signature" message-kill-to-signature t]
1553     ["Newline and Reformat" message-newline-and-reformat t]
1554     ["Rename buffer" message-rename-buffer t]
1555     ["Flag as important" message-insert-importance-high
1556      ,@(if (featurep 'xemacs) '(t)
1557          '(:help "Mark this message as important"))]
1558     ["Flag as unimportant" message-insert-importance-low
1559      ,@(if (featurep 'xemacs) '(t)
1560          '(:help "Mark this message as unimportant"))]
1561     ["Spellcheck" ispell-message
1562      ,@(if (featurep 'xemacs) '(t)
1563          '(:help "Spellcheck this message"))]
1564     "----"
1565     ["Send Message" message-send-and-exit
1566      ,@(if (featurep 'xemacs) '(t)
1567          '(:help "Send this message"))]
1568     ["Postpone Message" message-dont-send
1569      ,@(if (featurep 'xemacs) '(t)
1570          '(:help "File this draft message and exit"))]
1571     ["Send at Specific Time" gnus-delay-article
1572      ,@(if (featurep 'xemacs) '(t)
1573          '(:help "Ask, then arrange to send message at that time"))]
1574     ["Kill Message" message-kill-buffer
1575      ,@(if (featurep 'xemacs) '(t)
1576          '(:help "Delete this message without sending"))]))
1577
1578 (easy-menu-define
1579   message-mode-field-menu message-mode-map ""
1580   '("Field"
1581     ["Fetch To" message-insert-to t]
1582     ["Fetch Newsgroups" message-insert-newsgroups t]
1583     "----"
1584     ["To" message-goto-to t]
1585     ["Subject" message-goto-subject t]
1586     ["Cc" message-goto-cc t]
1587     ["Reply-To" message-goto-reply-to t]
1588     ["Summary" message-goto-summary t]
1589     ["Keywords" message-goto-keywords t]
1590     ["Newsgroups" message-goto-newsgroups t]
1591     ["Followup-To" message-goto-followup-to t]
1592     ["Mail-Followup-To" message-goto-mail-followup-to t]
1593     ["Distribution" message-goto-distribution t]
1594     ["Body" message-goto-body t]
1595     ["Signature" message-goto-signature t]))
1596
1597 (defvar message-tool-bar-map nil)
1598
1599 (eval-when-compile
1600   (defvar facemenu-add-face-function)
1601   (defvar facemenu-remove-face-function))
1602
1603 ;;; Forbidden properties
1604 ;;
1605 ;; We use `after-change-functions' to keep special text properties
1606 ;; that interfer with the normal function of message mode out of the
1607 ;; buffer. 
1608
1609 (defconst message-forbidden-properties 
1610   ;; No reason this should be clutter up customize.  We make it a
1611   ;; property list (rather than a list of property symbols), to be
1612   ;; directly useful for `remove-text-properties'.
1613   '(field nil read-only nil intangible nil invisible nil 
1614           mouse-face nil modification-hooks nil insert-in-front-hooks nil
1615           insert-behind-hooks nil point-entered nil point-left nil) 
1616   ;; Other special properties:
1617   ;; category, face, display: probably doesn't do any harm.
1618   ;; fontified: is used by font-lock.
1619   ;; syntax-table, local-map: I dunno.
1620   ;; We need to add XEmacs names to the list.
1621   "Property list of with properties.forbidden in message buffers.
1622 The values of the properties are ignored, only the property names are used.")
1623
1624 (defun message-strip-forbidden-properties (begin end &optional old-length)
1625   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
1626 This function is intended to be called from `after-change-functions'.
1627 See also `message-forbidden-properties'."
1628   (remove-text-properties begin end message-forbidden-properties))
1629
1630 ;;;###autoload
1631 (define-derived-mode message-mode text-mode "Message"
1632   "Major mode for editing mail and news to be sent.
1633 Like Text Mode but with these additional commands:\\<message-mode-map>
1634 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1635 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1636 C-c C-f  move to a header field (and create it if there isn't):
1637          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1638          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1639          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1640          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1641          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1642          C-c C-f C-f  move to Followup-To
1643          C-c C-f C-m  move to Mail-Followup-To
1644 C-c C-t  `message-insert-to' (add a To header to a news followup)
1645 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
1646 C-c C-b  `message-goto-body' (move to beginning of message text).
1647 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
1648 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
1649 C-c C-y  `message-yank-original' (insert current message, if any).
1650 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
1651 C-c C-e  `message-elide-region' (elide the text between point and mark).
1652 C-c C-v  `message-delete-not-region' (remove the text outside the region).
1653 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
1654 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
1655 C-c C-a  `mml-attach-file' (attach a file as MIME).
1656 C-c C-p  `message-insert-or-toggle-importance'  (insert or cycle importance)
1657 M-RET    `message-newline-and-reformat' (break the line and reformat)."
1658   (set (make-local-variable 'message-reply-buffer) nil)
1659   (make-local-variable 'message-send-actions)
1660   (make-local-variable 'message-exit-actions)
1661   (make-local-variable 'message-kill-actions)
1662   (make-local-variable 'message-postpone-actions)
1663   (make-local-variable 'message-draft-article)
1664   (setq buffer-offer-save t)
1665   (set (make-local-variable 'facemenu-add-face-function)
1666        (lambda (face end)
1667          (let ((face-fun (cdr (assq face message-face-alist))))
1668            (if face-fun
1669                (funcall face-fun (point) end)
1670              (error "Face %s not configured for %s mode" face mode-name)))
1671          ""))
1672   (set (make-local-variable 'facemenu-remove-face-function) t)
1673   (set (make-local-variable 'message-reply-headers) nil)
1674   (make-local-variable 'message-newsreader)
1675   (make-local-variable 'message-mailer)
1676   (make-local-variable 'message-post-method)
1677   (set (make-local-variable 'message-sent-message-via) nil)
1678   (set (make-local-variable 'message-checksum) nil)
1679   (set (make-local-variable 'message-mime-part) 0)
1680   (message-setup-fill-variables)
1681   ;; Allow using comment commands to add/remove quoting.
1682   (set (make-local-variable 'comment-start) message-yank-prefix)
1683   (if (featurep 'xemacs)
1684       (message-setup-toolbar)
1685     (set (make-local-variable 'font-lock-defaults)
1686          '(message-font-lock-keywords t))
1687     (if (boundp 'tool-bar-map)
1688         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1689   (easy-menu-add message-mode-menu message-mode-map)
1690   (easy-menu-add message-mode-field-menu message-mode-map)
1691   ;; Mmmm... Forbidden properties...
1692   (add-hook 'after-change-functions 'message-strip-forbidden-properties nil t)
1693   ;; Allow mail alias things.
1694   (when (eq message-mail-alias-type 'abbrev)
1695     (if (fboundp 'mail-abbrevs-setup)
1696         (mail-abbrevs-setup)
1697       (mail-aliases-setup)))
1698   (message-set-auto-save-file-name)
1699   (mm-enable-multibyte)
1700   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
1701   (mml-mode))
1702
1703 (defun message-setup-fill-variables ()
1704   "Setup message fill variables."
1705   (set (make-local-variable 'fill-paragraph-function)
1706        'message-fill-paragraph)
1707   (make-local-variable 'paragraph-separate)
1708   (make-local-variable 'paragraph-start)
1709   (make-local-variable 'adaptive-fill-regexp)
1710   (unless (boundp 'adaptive-fill-first-line-regexp)
1711     (setq adaptive-fill-first-line-regexp nil))
1712   (make-local-variable 'adaptive-fill-first-line-regexp)
1713   (let ((quote-prefix-regexp
1714          ;; User should change message-cite-prefix-regexp if
1715          ;; message-yank-prefix is set to an abnormal value.
1716          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
1717     (setq paragraph-start
1718           (concat
1719            (regexp-quote mail-header-separator) "$\\|"
1720            "[ \t]*$\\|"                 ; blank lines
1721            "-- $\\|"                    ; signature delimiter
1722            "---+$\\|"              ; delimiters for forwarded messages
1723            page-delimiter "$\\|"        ; spoiler warnings
1724            ".*wrote:$\\|"               ; attribution lines
1725            quote-prefix-regexp "$"))    ; empty lines in quoted text
1726     (setq paragraph-separate paragraph-start)
1727     (setq adaptive-fill-regexp
1728           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1729     (setq adaptive-fill-first-line-regexp
1730           (concat quote-prefix-regexp "\\|"
1731                   adaptive-fill-first-line-regexp)))
1732   (make-local-variable 'auto-fill-inhibit-regexp)
1733   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
1734   (setq auto-fill-inhibit-regexp nil)
1735   (make-local-variable 'normal-auto-fill-function)
1736   (setq normal-auto-fill-function 'message-do-auto-fill)
1737   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
1738   ;; In that case, ensure that it uses the right function.  The real
1739   ;; solution would be not to use `define-derived-mode', and run
1740   ;; `text-mode-hook' ourself at the end of the mode.
1741   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
1742   (when auto-fill-function
1743     (setq auto-fill-function normal-auto-fill-function)))
1744
1745 \f
1746
1747 ;;;
1748 ;;; Message mode commands
1749 ;;;
1750
1751 ;;; Movement commands
1752
1753 (defun message-goto-to ()
1754   "Move point to the To header."
1755   (interactive)
1756   (message-position-on-field "To"))
1757
1758 (defun message-goto-subject ()
1759   "Move point to the Subject header."
1760   (interactive)
1761   (message-position-on-field "Subject"))
1762
1763 (defun message-goto-cc ()
1764   "Move point to the Cc header."
1765   (interactive)
1766   (message-position-on-field "Cc" "To"))
1767
1768 (defun message-goto-bcc ()
1769   "Move point to the Bcc  header."
1770   (interactive)
1771   (message-position-on-field "Bcc" "Cc" "To"))
1772
1773 (defun message-goto-fcc ()
1774   "Move point to the Fcc header."
1775   (interactive)
1776   (message-position-on-field "Fcc" "To" "Newsgroups"))
1777
1778 (defun message-goto-reply-to ()
1779   "Move point to the Reply-To header."
1780   (interactive)
1781   (message-position-on-field "Reply-To" "Subject"))
1782
1783 (defun message-goto-newsgroups ()
1784   "Move point to the Newsgroups header."
1785   (interactive)
1786   (message-position-on-field "Newsgroups"))
1787
1788 (defun message-goto-distribution ()
1789   "Move point to the Distribution header."
1790   (interactive)
1791   (message-position-on-field "Distribution"))
1792
1793 (defun message-goto-followup-to ()
1794   "Move point to the Followup-To header."
1795   (interactive)
1796   (message-position-on-field "Followup-To" "Newsgroups"))
1797
1798 (defun message-goto-mail-followup-to ()
1799   "Move point to the Mail-Followup-To header."
1800   (interactive)
1801   (message-position-on-field "Mail-Followup-To" "From"))
1802
1803 (defun message-goto-keywords ()
1804   "Move point to the Keywords header."
1805   (interactive)
1806   (message-position-on-field "Keywords" "Subject"))
1807
1808 (defun message-goto-summary ()
1809   "Move point to the Summary header."
1810   (interactive)
1811   (message-position-on-field "Summary" "Subject"))
1812
1813 (defun message-goto-body (&optional interactivep)
1814   "Move point to the beginning of the message body."
1815   (interactive (list t))
1816   (when (and interactivep
1817              (looking-at "[ \t]*\n"))
1818     (expand-abbrev))
1819   (goto-char (point-min))
1820   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1821       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
1822
1823 (defun message-goto-eoh ()
1824   "Move point to the end of the headers."
1825   (interactive)
1826   (message-goto-body)
1827   (forward-line -1))
1828
1829 (defun message-goto-signature ()
1830   "Move point to the beginning of the message signature.
1831 If there is no signature in the article, go to the end and
1832 return nil."
1833   (interactive)
1834   (goto-char (point-min))
1835   (if (re-search-forward message-signature-separator nil t)
1836       (forward-line 1)
1837     (goto-char (point-max))
1838     nil))
1839
1840 \f
1841
1842 (defun message-insert-to (&optional force)
1843   "Insert a To header that points to the author of the article being replied to.
1844 If the original author requested not to be sent mail, the function signals
1845 an error.
1846 With the prefix argument FORCE, insert the header anyway."
1847   (interactive "P")
1848   (let ((co (message-fetch-reply-field "mail-copies-to")))
1849     (when (and (null force)
1850                co
1851                (or (equal (downcase co) "never")
1852                    (equal (downcase co) "nobody")))
1853       (error "The user has requested not to have copies sent via mail")))
1854   (when (and (message-position-on-field "To")
1855              (mail-fetch-field "to")
1856              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1857     (insert ", "))
1858   (insert (or (message-fetch-reply-field "mail-reply-to")
1859               (message-fetch-reply-field "reply-to")
1860               (message-fetch-reply-field "from") "")))
1861
1862 (defun message-widen-reply ()
1863   "Widen the reply to include maximum recipients."
1864   (interactive)
1865   (let ((follow-to
1866          (and message-reply-buffer
1867               (buffer-name message-reply-buffer)
1868               (save-excursion
1869                 (set-buffer message-reply-buffer)
1870                 (message-get-reply-headers t)))))
1871     (save-excursion
1872       (save-restriction
1873         (message-narrow-to-headers)
1874         (dolist (elem follow-to)
1875           (message-remove-header (symbol-name (car elem)))
1876           (goto-char (point-min))
1877           (insert (symbol-name (car elem)) ": "
1878                   (cdr elem) "\n"))))))
1879
1880 (defun message-insert-newsgroups ()
1881   "Insert the Newsgroups header from the article being replied to."
1882   (interactive)
1883   (when (and (message-position-on-field "Newsgroups")
1884              (mail-fetch-field "newsgroups")
1885              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1886     (insert ","))
1887   (insert (or (message-fetch-reply-field "newsgroups") "")))
1888
1889 \f
1890
1891 ;;; Various commands
1892
1893 (defun message-delete-not-region (beg end)
1894   "Delete everything in the body of the current message outside of the region."
1895   (interactive "r")
1896   (let (citeprefix)
1897     (save-excursion
1898       (goto-char beg)
1899       ;; snarf citation prefix, if appropriate
1900       (unless (eq (point) (progn (beginning-of-line) (point)))
1901         (when (looking-at message-cite-prefix-regexp)
1902           (setq citeprefix (match-string 0))))
1903       (goto-char end)
1904       (delete-region (point) (if (not (message-goto-signature))
1905                                  (point)
1906                                (forward-line -2)
1907                                (point)))
1908       (insert "\n")
1909       (goto-char beg)
1910       (delete-region beg (progn (message-goto-body)
1911                                 (forward-line 2)
1912                                 (point)))
1913       (when citeprefix
1914         (insert citeprefix))))
1915   (when (message-goto-signature)
1916     (forward-line -2)))
1917
1918 (defun message-kill-to-signature ()
1919   "Deletes all text up to the signature."
1920   (interactive)
1921   (let ((point (point)))
1922     (message-goto-signature)
1923     (unless (eobp)
1924       (forward-line -2))
1925     (kill-region point (point))
1926     (unless (bolp)
1927       (insert "\n"))))
1928
1929 (defun message-newline-and-reformat (&optional arg not-break)
1930   "Insert four newlines, and then reformat if inside quoted text.
1931 Prefix arg means justify as well."
1932   (interactive (list (if current-prefix-arg 'full)))
1933   (let (quoted point beg end leading-space bolp)
1934     (setq point (point))
1935     (beginning-of-line)
1936     (setq beg (point))
1937     (setq bolp (= beg point))
1938     ;; Find first line of the paragraph.
1939     (if not-break
1940         (while (and (not (eobp))
1941                     (not (looking-at message-cite-prefix-regexp))
1942                     (looking-at paragraph-start))
1943           (forward-line 1)))
1944     ;; Find the prefix
1945     (when (looking-at message-cite-prefix-regexp)
1946       (setq quoted (match-string 0))
1947       (goto-char (match-end 0))
1948       (looking-at "[ \t]*")
1949       (setq leading-space (match-string 0)))
1950     (if (and quoted
1951              (not not-break)
1952              (not bolp)
1953              (< (- point beg) (length quoted)))
1954         ;; break inside the cite prefix.
1955         (setq quoted nil
1956               end nil))
1957     (if quoted
1958         (progn
1959           (forward-line 1)
1960           (while (and (not (eobp))
1961                       (not (looking-at paragraph-separate))
1962                       (looking-at message-cite-prefix-regexp)
1963                       (equal quoted (match-string 0)))
1964             (goto-char (match-end 0))
1965             (looking-at "[ \t]*")
1966             (if (> (length leading-space) (length (match-string 0)))
1967                 (setq leading-space (match-string 0)))
1968             (forward-line 1))
1969           (setq end (point))
1970           (goto-char beg)
1971           (while (and (if (bobp) nil (forward-line -1) t)
1972                       (not (looking-at paragraph-start))
1973                       (looking-at message-cite-prefix-regexp)
1974                       (equal quoted (match-string 0)))
1975             (setq beg (point))
1976             (goto-char (match-end 0))
1977             (looking-at "[ \t]*")
1978             (if (> (length leading-space) (length (match-string 0)))
1979                 (setq leading-space (match-string 0)))))
1980       (while (and (not (eobp))
1981                   (not (looking-at paragraph-separate))
1982                   (not (looking-at message-cite-prefix-regexp)))
1983         (forward-line 1))
1984       (setq end (point))
1985       (goto-char beg)
1986       (while (and (if (bobp) nil (forward-line -1) t)
1987                   (not (looking-at paragraph-start))
1988                   (not (looking-at message-cite-prefix-regexp)))
1989         (setq beg (point))))
1990     (goto-char point)
1991     (save-restriction
1992       (narrow-to-region beg end)
1993       (if not-break
1994           (setq point nil)
1995         (if bolp
1996             (insert "\n")
1997           (insert "\n\n"))
1998         (setq point (point))
1999         (insert "\n\n")
2000         (delete-region (point) (re-search-forward "[ \t]*"))
2001         (when (and quoted (not bolp))
2002           (insert quoted leading-space)))
2003       (if quoted
2004           (let* ((adaptive-fill-regexp
2005                   (regexp-quote (concat quoted leading-space)))
2006                  (adaptive-fill-first-line-regexp
2007                   adaptive-fill-regexp ))
2008             (fill-paragraph arg))
2009         (fill-paragraph arg))
2010       (if point (goto-char point)))))
2011
2012 (defun message-fill-paragraph (&optional arg)
2013   "Like `fill-paragraph'."
2014   (interactive (list (if current-prefix-arg 'full)))
2015   (if (and (boundp 'filladapt-mode) filladapt-mode)
2016       nil
2017     (message-newline-and-reformat arg t)
2018     t))
2019
2020 ;; Is it better to use `mail-header-end'?
2021 (defun message-point-in-header-p ()
2022   "Return t if point is in the header."
2023   (save-excursion
2024     (let ((p (point)))
2025       (goto-char (point-min))
2026       (not (re-search-forward
2027             (concat "^" (regexp-quote mail-header-separator) "\n")
2028             p t)))))
2029
2030 (defun message-do-auto-fill ()
2031   "Like `do-auto-fill', but don't fill in message header."
2032   (unless (message-point-in-header-p)
2033     (do-auto-fill)))
2034
2035 (defun message-insert-signature (&optional force)
2036   "Insert a signature.  See documentation for variable `message-signature'."
2037   (interactive (list 0))
2038   (let* ((signature
2039           (cond
2040            ((and (null message-signature)
2041                  (eq force 0))
2042             (save-excursion
2043               (goto-char (point-max))
2044               (not (re-search-backward message-signature-separator nil t))))
2045            ((and (null message-signature)
2046                  force)
2047             t)
2048            ((message-functionp message-signature)
2049             (funcall message-signature))
2050            ((listp message-signature)
2051             (eval message-signature))
2052            (t message-signature)))
2053          (signature
2054           (cond ((stringp signature)
2055                  signature)
2056                 ((and (eq t signature)
2057                       message-signature-file
2058                       (file-exists-p message-signature-file))
2059                  signature))))
2060     (when signature
2061       (goto-char (point-max))
2062       ;; Insert the signature.
2063       (unless (bolp)
2064         (insert "\n"))
2065       (insert "\n-- \n")
2066       (if (eq signature t)
2067           (insert-file-contents message-signature-file)
2068         (insert signature))
2069       (goto-char (point-max))
2070       (or (bolp) (insert "\n")))))
2071
2072 (defun message-insert-importance-high ()
2073   "Insert header to mark message as important."
2074   (interactive)
2075   (message-remove-header "Importance")
2076   (message-goto-eoh)
2077   (insert "Importance: high\n"))
2078
2079 (defun message-insert-importance-low ()
2080   "Insert header to mark message as unimportant."
2081   (interactive)
2082   (message-remove-header "Importance")
2083   (message-goto-eoh)
2084   (insert "Importance: low\n"))
2085
2086 (defun message-insert-or-toggle-importance ()
2087   "Insert a \"Importance: high\" header, or cycle through the header values.
2088 The three allowed values according to RFC 1327 are `high', `normal'
2089 and `low'."
2090   (interactive)
2091   (save-excursion
2092     (let ((valid '("high" "normal" "low"))
2093           (new "high")
2094           cur)
2095       (when (setq cur (message-fetch-field "Importance"))
2096         (message-remove-header "Importance")
2097         (setq new (cond ((string= cur "high")
2098                          "low")
2099                         ((string= cur "low")
2100                          "normal")
2101                         (t
2102                          "high"))))
2103       (message-goto-eoh)
2104       (insert (format "Importance: %s\n" new)))))
2105
2106 (defun message-elide-region (b e)
2107   "Elide the text in the region.
2108 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2109 text was killed."
2110   (interactive "r")
2111   (kill-region b e)
2112   (insert message-elide-ellipsis))
2113
2114 (defvar message-caesar-translation-table nil)
2115
2116 (defun message-caesar-region (b e &optional n)
2117   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2118   (interactive
2119    (list
2120     (min (point) (or (mark t) (point)))
2121     (max (point) (or (mark t) (point)))
2122     (when current-prefix-arg
2123       (prefix-numeric-value current-prefix-arg))))
2124
2125   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2126   (unless (or (zerop n)                 ; no action needed for a rot of 0
2127               (= b e))                  ; no region to rotate
2128     ;; We build the table, if necessary.
2129     (when (or (not message-caesar-translation-table)
2130               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2131       (setq message-caesar-translation-table
2132             (message-make-caesar-translation-table n)))
2133     (translate-region b e message-caesar-translation-table)))
2134
2135 (defun message-make-caesar-translation-table (n)
2136   "Create a rot table with offset N."
2137   (let ((i -1)
2138         (table (make-string 256 0)))
2139     (while (< (incf i) 256)
2140       (aset table i i))
2141     (concat
2142      (substring table 0 ?A)
2143      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2144      (substring table ?A (+ ?A n))
2145      (substring table (+ ?A 26) ?a)
2146      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2147      (substring table ?a (+ ?a n))
2148      (substring table (+ ?a 26) 255))))
2149
2150 (defun message-caesar-buffer-body (&optional rotnum)
2151   "Caesar rotate all letters in the current buffer by 13 places.
2152 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2153 With prefix arg, specifies the number of places to rotate each letter forward.
2154 Mail and USENET news headers are not rotated."
2155   (interactive (if current-prefix-arg
2156                    (list (prefix-numeric-value current-prefix-arg))
2157                  (list nil)))
2158   (save-excursion
2159     (save-restriction
2160       (when (message-goto-body)
2161         (narrow-to-region (point) (point-max)))
2162       (message-caesar-region (point-min) (point-max) rotnum))))
2163
2164 (defun message-pipe-buffer-body (program)
2165   "Pipe the message body in the current buffer through PROGRAM."
2166   (save-excursion
2167     (save-restriction
2168       (when (message-goto-body)
2169         (narrow-to-region (point) (point-max)))
2170       (shell-command-on-region
2171        (point-min) (point-max) program nil t))))
2172
2173 (defun message-rename-buffer (&optional enter-string)
2174   "Rename the *message* buffer to \"*message* RECIPIENT\".
2175 If the function is run with a prefix, it will ask for a new buffer
2176 name, rather than giving an automatic name."
2177   (interactive "Pbuffer name: ")
2178   (save-excursion
2179     (save-restriction
2180       (goto-char (point-min))
2181       (narrow-to-region (point)
2182                         (search-forward mail-header-separator nil 'end))
2183       (let* ((mail-to (or
2184                        (if (message-news-p) (message-fetch-field "Newsgroups")
2185                          (message-fetch-field "To"))
2186                        ""))
2187              (mail-trimmed-to
2188               (if (string-match "," mail-to)
2189                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2190                 mail-to))
2191              (name-default (concat "*message* " mail-trimmed-to))
2192              (name (if enter-string
2193                        (read-string "New buffer name: " name-default)
2194                      name-default)))
2195         (rename-buffer name t)))))
2196
2197 (defun message-fill-yanked-message (&optional justifyp)
2198   "Fill the paragraphs of a message yanked into this one.
2199 Numeric argument means justify as well."
2200   (interactive "P")
2201   (save-excursion
2202     (goto-char (point-min))
2203     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2204     (let ((fill-prefix message-yank-prefix))
2205       (fill-individual-paragraphs (point) (point-max) justifyp))))
2206
2207 (defun message-indent-citation ()
2208   "Modify text just inserted from a message to be cited.
2209 The inserted text should be the region.
2210 When this function returns, the region is again around the modified text.
2211
2212 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2213 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2214   (let ((start (point)))
2215     ;; Remove unwanted headers.
2216     (when message-ignored-cited-headers
2217       (let (all-removed)
2218         (save-restriction
2219           (narrow-to-region
2220            (goto-char start)
2221            (if (search-forward "\n\n" nil t)
2222                (1- (point))
2223              (point)))
2224           (message-remove-header message-ignored-cited-headers t)
2225           (when (= (point-min) (point-max))
2226             (setq all-removed t))
2227           (goto-char (point-max)))
2228         (if all-removed
2229             (goto-char start)
2230           (forward-line 1))))
2231     ;; Delete blank lines at the start of the buffer.
2232     (while (and (point-min)
2233                 (eolp)
2234                 (not (eobp)))
2235       (message-delete-line))
2236     ;; Delete blank lines at the end of the buffer.
2237     (goto-char (point-max))
2238     (unless (eolp)
2239       (insert "\n"))
2240     (while (and (zerop (forward-line -1))
2241                 (looking-at "$"))
2242       (message-delete-line))
2243     ;; Do the indentation.
2244     (if (null message-yank-prefix)
2245         (indent-rigidly start (mark t) message-indentation-spaces)
2246       (save-excursion
2247         (goto-char start)
2248         (while (< (point) (mark t))
2249           (if (or (looking-at ">") (looking-at "^$"))
2250               (insert message-yank-cited-prefix)
2251             (insert message-yank-prefix))
2252           (forward-line 1))))
2253     (goto-char start)))
2254
2255 (defun message-yank-original (&optional arg)
2256   "Insert the message being replied to, if any.
2257 Puts point before the text and mark after.
2258 Normally indents each nonblank line ARG spaces (default 3).  However,
2259 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2260
2261 This function uses `message-cite-function' to do the actual citing.
2262
2263 Just \\[universal-argument] as argument means don't indent, insert no
2264 prefix, and don't delete any headers."
2265   (interactive "P")
2266   (let ((modified (buffer-modified-p)))
2267     (when (and message-reply-buffer
2268                message-cite-function)
2269       (delete-windows-on message-reply-buffer t)
2270       (insert-buffer message-reply-buffer)
2271       (unless arg
2272         (funcall message-cite-function))
2273       (message-exchange-point-and-mark)
2274       (unless (bolp)
2275         (insert ?\n))
2276       (unless modified
2277         (setq message-checksum (message-checksum))))))
2278
2279 (defun message-yank-buffer (buffer)
2280   "Insert BUFFER into the current buffer and quote it."
2281   (interactive "bYank buffer: ")
2282   (let ((message-reply-buffer buffer))
2283     (save-window-excursion
2284       (message-yank-original))))
2285
2286 (defun message-buffers ()
2287   "Return a list of active message buffers."
2288   (let (buffers)
2289     (save-excursion
2290       (dolist (buffer (buffer-list t))
2291         (set-buffer buffer)
2292         (when (and (eq major-mode 'message-mode)
2293                    (null message-sent-message-via))
2294           (push (buffer-name buffer) buffers))))
2295     (nreverse buffers)))
2296
2297 (defun message-cite-original-without-signature ()
2298   "Cite function in the standard Message manner."
2299   (let ((start (point))
2300         (end (mark t))
2301         (functions
2302          (when message-indent-citation-function
2303            (if (listp message-indent-citation-function)
2304                message-indent-citation-function
2305              (list message-indent-citation-function)))))
2306     (mml-quote-region start end)
2307     ;; Allow undoing.
2308     (undo-boundary)
2309     (goto-char end)
2310     (when (re-search-backward message-signature-separator start t)
2311       ;; Also peel off any blank lines before the signature.
2312       (forward-line -1)
2313       (while (looking-at "^[ \t]*$")
2314         (forward-line -1))
2315       (forward-line 1)
2316       (delete-region (point) end)
2317       (unless (search-backward "\n\n" start t)
2318         ;; Insert a blank line if it is peeled off.
2319         (insert "\n")))
2320     (goto-char start)
2321     (while functions
2322       (funcall (pop functions)))
2323     (when message-citation-line-function
2324       (unless (bolp)
2325         (insert "\n"))
2326       (funcall message-citation-line-function))))
2327
2328 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
2329 (defun message-cite-original ()
2330   "Cite function in the standard Message manner."
2331   (if (and (boundp 'mail-citation-hook)
2332            mail-citation-hook)
2333       (run-hooks 'mail-citation-hook)
2334     (let ((start (point))
2335           (end (mark t))
2336           (functions
2337            (when message-indent-citation-function
2338              (if (listp message-indent-citation-function)
2339                  message-indent-citation-function
2340                (list message-indent-citation-function)))))
2341       (mml-quote-region start end)
2342       (goto-char start)
2343       (while functions
2344         (funcall (pop functions)))
2345       (when message-citation-line-function
2346         (unless (bolp)
2347           (insert "\n"))
2348         (funcall message-citation-line-function)))))
2349
2350 (defun message-insert-citation-line ()
2351   "Insert a simple citation line."
2352   (when message-reply-headers
2353     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2354
2355 (defun message-position-on-field (header &rest afters)
2356   (let ((case-fold-search t))
2357     (save-restriction
2358       (narrow-to-region
2359        (goto-char (point-min))
2360        (progn
2361          (re-search-forward
2362           (concat "^" (regexp-quote mail-header-separator) "$"))
2363          (match-beginning 0)))
2364       (goto-char (point-min))
2365       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2366           (progn
2367             (re-search-forward "^[^ \t]" nil 'move)
2368             (beginning-of-line)
2369             (skip-chars-backward "\n")
2370             t)
2371         (while (and afters
2372                     (not (re-search-forward
2373                           (concat "^" (regexp-quote (car afters)) ":")
2374                           nil t)))
2375           (pop afters))
2376         (when afters
2377           (re-search-forward "^[^ \t]" nil 'move)
2378           (beginning-of-line))
2379         (insert header ": \n")
2380         (forward-char -1)
2381         nil))))
2382
2383 (defun message-remove-signature ()
2384   "Remove the signature from the text between point and mark.
2385 The text will also be indented the normal way."
2386   (save-excursion
2387     (let ((start (point))
2388           mark)
2389       (if (not (re-search-forward message-signature-separator (mark t) t))
2390           ;; No signature here, so we just indent the cited text.
2391           (message-indent-citation)
2392         ;; Find the last non-empty line.
2393         (forward-line -1)
2394         (while (looking-at "[ \t]*$")
2395           (forward-line -1))
2396         (forward-line 1)
2397         (setq mark (set-marker (make-marker) (point)))
2398         (goto-char start)
2399         (message-indent-citation)
2400         ;; Enable undoing the deletion.
2401         (undo-boundary)
2402         (delete-region mark (mark t))
2403         (set-marker mark nil)))))
2404
2405 \f
2406
2407 ;;;
2408 ;;; Sending messages
2409 ;;;
2410
2411 (defun message-send-and-exit (&optional arg)
2412   "Send message like `message-send', then, if no errors, exit from mail buffer."
2413   (interactive "P")
2414   (let ((buf (current-buffer))
2415         (actions message-exit-actions))
2416     (when (and (message-send arg)
2417                (buffer-name buf))
2418       (if message-kill-buffer-on-exit
2419           (kill-buffer buf)
2420         (bury-buffer buf)
2421         (when (eq buf (current-buffer))
2422           (message-bury buf)))
2423       (message-do-actions actions)
2424       t)))
2425
2426 (defun message-dont-send ()
2427   "Don't send the message you have been editing."
2428   (interactive)
2429   (set-buffer-modified-p t)
2430   (save-buffer)
2431   (let ((actions message-postpone-actions))
2432     (message-bury (current-buffer))
2433     (message-do-actions actions)))
2434
2435 (defun message-kill-buffer ()
2436   "Kill the current buffer."
2437   (interactive)
2438   (when (or (not (buffer-modified-p))
2439             (yes-or-no-p "Message modified; kill anyway? "))
2440     (let ((actions message-kill-actions)
2441           (draft-article message-draft-article)
2442           (auto-save-file-name buffer-auto-save-file-name)
2443           (file-name buffer-file-name)
2444           (modified (buffer-modified-p)))
2445       (setq buffer-file-name nil)
2446       (kill-buffer (current-buffer))
2447       (when (and (or (and auto-save-file-name
2448                           (file-exists-p auto-save-file-name))
2449                      (and file-name
2450                           (file-exists-p file-name)))
2451                (yes-or-no-p (format "Remove the backup file%s? "
2452                                     (if modified " too" ""))))
2453         (ignore-errors
2454           (delete-file auto-save-file-name))
2455         (let ((message-draft-article draft-article))
2456           (message-disassociate-draft)))
2457       (message-do-actions actions))))
2458
2459 (defun message-bury (buffer)
2460   "Bury this mail BUFFER."
2461   (let ((newbuf (other-buffer buffer)))
2462     (bury-buffer buffer)
2463     (if (and (fboundp 'frame-parameters)
2464              (cdr (assq 'dedicated (frame-parameters)))
2465              (not (null (delq (selected-frame) (visible-frame-list)))))
2466         (delete-frame (selected-frame))
2467       (switch-to-buffer newbuf))))
2468
2469 (defun message-send (&optional arg)
2470   "Send the message in the current buffer.
2471 If `message-interactive' is non-nil, wait for success indication or
2472 error messages, and inform user.
2473 Otherwise any failure is reported in a message back to the user from
2474 the mailer.
2475 The usage of ARG is defined by the instance that called Message.
2476 It should typically alter the sending method in some way or other."
2477   (interactive "P")
2478   ;; Make it possible to undo the coming changes.
2479   (undo-boundary)
2480   (let ((inhibit-read-only t))
2481     (put-text-property (point-min) (point-max) 'read-only nil))
2482   (message-fix-before-sending)
2483   (run-hooks 'message-send-hook)
2484   (message message-sending-message)
2485   (let ((alist message-send-method-alist)
2486         (success t)
2487         elem sent
2488         (message-options message-options))
2489     (message-options-set-recipient)
2490     (while (and success
2491                 (setq elem (pop alist)))
2492       (when (funcall (cadr elem))
2493         (when (and (or (not (memq (car elem)
2494                                   message-sent-message-via))
2495                        (if (or (message-gnksa-enable-p 'multiple-copies)
2496                                (not (eq (car elem) 'news)))
2497                            (y-or-n-p
2498                             (format
2499                              "Already sent message via %s; resend? "
2500                              (car elem)))
2501                          (error "Denied posting -- multiple copies")))
2502                    (setq success (funcall (caddr elem) arg)))
2503           (setq sent t))))
2504     (unless (or sent (not success))
2505       (error "No methods specified to send by"))
2506     (when (and success sent)
2507       (message-do-fcc)
2508       (save-excursion
2509         (run-hooks 'message-sent-hook))
2510       (message "Sending...done")
2511       ;; Mark the buffer as unmodified and delete auto-save.
2512       (set-buffer-modified-p nil)
2513       (delete-auto-save-file-if-necessary t)
2514       (message-disassociate-draft)
2515       ;; Delete other mail buffers and stuff.
2516       (message-do-send-housekeeping)
2517       (message-do-actions message-send-actions)
2518       ;; Return success.
2519       t)))
2520
2521 (defun message-send-via-mail (arg)
2522   "Send the current message via mail."
2523   (message-send-mail arg))
2524
2525 (defun message-send-via-news (arg)
2526   "Send the current message via news."
2527   (funcall message-send-news-function arg))
2528
2529 (defmacro message-check (type &rest forms)
2530   "Eval FORMS if TYPE is to be checked."
2531   `(or (message-check-element ,type)
2532        (save-excursion
2533          ,@forms)))
2534
2535 (put 'message-check 'lisp-indent-function 1)
2536 (put 'message-check 'edebug-form-spec '(form body))
2537
2538 (defun message-fix-before-sending ()
2539   "Do various things to make the message nice before sending it."
2540   ;; Make sure there's a newline at the end of the message.
2541   (goto-char (point-max))
2542   (unless (bolp)
2543     (insert "\n"))
2544   ;; Delete all invisible text.
2545   (message-check 'invisible-text
2546     (when (text-property-any (point-min) (point-max) 'invisible t)
2547       (put-text-property (point-min) (point-max) 'invisible nil)
2548       (unless (yes-or-no-p
2549                "Invisible text found and made visible; continue posting? ")
2550         (error "Invisible text found and made visible")))))
2551
2552 (defun message-add-action (action &rest types)
2553   "Add ACTION to be performed when doing an exit of type TYPES."
2554   (let (var)
2555     (while types
2556       (set (setq var (intern (format "message-%s-actions" (pop types))))
2557            (nconc (symbol-value var) (list action))))))
2558
2559 (defun message-do-actions (actions)
2560   "Perform all actions in ACTIONS."
2561   ;; Now perform actions on successful sending.
2562   (while actions
2563     (ignore-errors
2564       (cond
2565        ;; A simple function.
2566        ((message-functionp (car actions))
2567         (funcall (car actions)))
2568        ;; Something to be evaled.
2569        (t
2570         (eval (car actions)))))
2571     (pop actions)))
2572
2573 (defun message-send-mail-partially ()
2574   "Send mail as message/partial."
2575   ;; replace the header delimiter with a blank line
2576   (goto-char (point-min))
2577   (re-search-forward
2578    (concat "^" (regexp-quote mail-header-separator) "\n"))
2579   (replace-match "\n")
2580   (run-hooks 'message-send-mail-hook)
2581   (let ((p (goto-char (point-min)))
2582         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2583         (curbuf (current-buffer))
2584         (id (message-make-message-id)) (n 1)
2585         plist total  header required-mail-headers)
2586     (while (not (eobp))
2587       (if (< (point-max) (+ p message-send-mail-partially-limit))
2588           (goto-char (point-max))
2589         (goto-char (+ p message-send-mail-partially-limit))
2590         (beginning-of-line)
2591         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2592       (push p plist)
2593       (setq p (point)))
2594     (setq total (length plist))
2595     (push (point-max) plist)
2596     (setq plist (nreverse plist))
2597     (unwind-protect
2598         (save-excursion
2599           (setq p (pop plist))
2600           (while plist
2601             (set-buffer curbuf)
2602             (copy-to-buffer tembuf p (car plist))
2603             (set-buffer tembuf)
2604             (goto-char (point-min))
2605             (if header
2606                 (progn
2607                   (goto-char (point-min))
2608                   (narrow-to-region (point) (point))
2609                   (insert header))
2610               (message-goto-eoh)
2611               (setq header (buffer-substring (point-min) (point)))
2612               (goto-char (point-min))
2613               (narrow-to-region (point) (point))
2614               (insert header)
2615               (message-remove-header "Mime-Version")
2616               (message-remove-header "Content-Type")
2617               (message-remove-header "Content-Transfer-Encoding")
2618               (message-remove-header "Message-ID")
2619               (message-remove-header "Lines")
2620               (goto-char (point-max))
2621               (insert "Mime-Version: 1.0\n")
2622               (setq header (buffer-substring (point-min) (point-max))))
2623             (goto-char (point-max))
2624             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
2625                             id n total))
2626             (forward-char -1)
2627             (let ((mail-header-separator ""))
2628               (when (memq 'Message-ID message-required-mail-headers)
2629                 (insert "Message-ID: " (message-make-message-id) "\n"))
2630               (when (memq 'Lines message-required-mail-headers)
2631                 (insert "Lines: " (message-make-lines) "\n"))
2632               (message-goto-subject)
2633               (end-of-line)
2634               (insert (format " (%d/%d)" n total))
2635               (widen)
2636               (mm-with-unibyte-current-buffer
2637                 (funcall (or message-send-mail-real-function
2638                              message-send-mail-function))))
2639             (setq n (+ n 1))
2640             (setq p (pop plist))
2641             (erase-buffer)))
2642       (kill-buffer tembuf))))
2643
2644 (defun message-send-mail (&optional arg)
2645   (require 'mail-utils)
2646   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2647          (case-fold-search nil)
2648          (news (message-news-p))
2649          (mailbuf (current-buffer))
2650          (message-this-is-mail t)
2651          (message-posting-charset
2652           (if (fboundp 'gnus-setup-posting-charset)
2653               (gnus-setup-posting-charset nil)
2654             message-posting-charset))
2655          (headers message-required-mail-headers))
2656     (save-restriction
2657       (message-narrow-to-headers)
2658       ;; Generate the Mail-Followup-To header if the header is not there...
2659       (if (and (or message-subscribed-regexps
2660                    message-subscribed-addresses
2661                    message-subscribed-address-functions)
2662                (not (mail-fetch-field "mail-followup-to")))
2663           (setq headers
2664                 (cons
2665                  (cons "Mail-Followup-To" (message-make-mft))
2666                  message-required-mail-headers))
2667         ;; otherwise, delete the MFT header if the field is empty
2668         (when (equal "" (mail-fetch-field "mail-followup-to"))
2669           (message-remove-header "^Mail-Followup-To:")))
2670       ;; Insert some headers.
2671       (let ((message-deletable-headers
2672              (if news nil message-deletable-headers)))
2673         (message-generate-headers headers))
2674       ;; Let the user do all of the above.
2675       (run-hooks 'message-header-hook))
2676     (unwind-protect
2677         (save-excursion
2678           (set-buffer tembuf)
2679           (erase-buffer)
2680           ;; Avoid copying text props.
2681           (insert (with-current-buffer mailbuf
2682                     (buffer-substring-no-properties (point-min) (point-max))))
2683           ;; Remove some headers.
2684           (message-encode-message-body)
2685           (save-restriction
2686             (message-narrow-to-headers)
2687             ;; We (re)generate the Lines header.
2688             (when (memq 'Lines message-required-mail-headers)
2689               (message-generate-headers '(Lines)))
2690             ;; Remove some headers.
2691             (message-remove-header message-ignored-mail-headers t)
2692             (let ((mail-parse-charset message-default-charset))
2693               (mail-encode-encoded-word-buffer)))
2694           (goto-char (point-max))
2695           ;; require one newline at the end.
2696           (or (= (preceding-char) ?\n)
2697               (insert ?\n))
2698           (when
2699               (save-restriction
2700                 (message-narrow-to-headers)
2701                 (and news
2702                      (or (message-fetch-field "cc")
2703                          (message-fetch-field "to"))
2704                      (let ((content-type (message-fetch-field "content-type")))
2705                        (or
2706                         (not content-type)
2707                         (string= "text/plain"
2708                                  (car
2709                                   (mail-header-parse-content-type
2710                                    content-type)))))))
2711             (message-insert-courtesy-copy))
2712           (if (or (not message-send-mail-partially-limit)
2713                   (< (point-max) message-send-mail-partially-limit)
2714                   (not (y-or-n-p "Message exceeds message-send-mail-partially-limit, send in parts? ")))
2715               (mm-with-unibyte-current-buffer
2716                 (message "Sending via mail...")
2717                 (funcall (or message-send-mail-real-function
2718                              message-send-mail-function)))
2719             (message-send-mail-partially)))
2720       (kill-buffer tembuf))
2721     (set-buffer mailbuf)
2722     (push 'mail message-sent-message-via)))
2723
2724 (defun message-send-mail-with-sendmail ()
2725   "Send off the prepared buffer with sendmail."
2726   (let ((errbuf (if message-interactive
2727                     (message-generate-new-buffer-clone-locals
2728                      " sendmail errors")
2729                   0))
2730         resend-to-addresses delimline)
2731     (let ((case-fold-search t))
2732       (save-restriction
2733         (message-narrow-to-headers)
2734         (setq resend-to-addresses (message-fetch-field "resent-to")))
2735       ;; Change header-delimiter to be what sendmail expects.
2736       (goto-char (point-min))
2737       (re-search-forward
2738        (concat "^" (regexp-quote mail-header-separator) "\n"))
2739       (replace-match "\n")
2740       (backward-char 1)
2741       (setq delimline (point-marker))
2742       (run-hooks 'message-send-mail-hook)
2743       ;; Insert an extra newline if we need it to work around
2744       ;; Sun's bug that swallows newlines.
2745       (goto-char (1+ delimline))
2746       (when (eval message-mailer-swallows-blank-line)
2747         (newline))
2748       (when message-interactive
2749         (save-excursion
2750           (set-buffer errbuf)
2751           (erase-buffer))))
2752     (let ((default-directory "/")
2753           (coding-system-for-write message-send-coding-system))
2754       (apply 'call-process-region
2755              (append (list (point-min) (point-max)
2756                            (if (boundp 'sendmail-program)
2757                                sendmail-program
2758                              "/usr/lib/sendmail")
2759                            nil errbuf nil "-oi")
2760                      ;; Always specify who from,
2761                      ;; since some systems have broken sendmails.
2762                      ;; But some systems are more broken with -f, so
2763                      ;; we'll let users override this.
2764                      (if (null message-sendmail-f-is-evil)
2765                          (list "-f" (message-make-address)))
2766                      ;; These mean "report errors by mail"
2767                      ;; and "deliver in background".
2768                      (if (null message-interactive) '("-oem" "-odb"))
2769                      ;; Get the addresses from the message
2770                      ;; unless this is a resend.
2771                      ;; We must not do that for a resend
2772                      ;; because we would find the original addresses.
2773                      ;; For a resend, include the specific addresses.
2774                      (if resend-to-addresses
2775                          (list resend-to-addresses)
2776                        '("-t")))))
2777     (when message-interactive
2778       (save-excursion
2779         (set-buffer errbuf)
2780         (goto-char (point-min))
2781         (while (re-search-forward "\n\n* *" nil t)
2782           (replace-match "; "))
2783         (if (not (zerop (buffer-size)))
2784             (error "Sending...failed to %s"
2785                    (buffer-substring (point-min) (point-max)))))
2786       (when (bufferp errbuf)
2787         (kill-buffer errbuf)))))
2788
2789 (defun message-send-mail-with-qmail ()
2790   "Pass the prepared message buffer to qmail-inject.
2791 Refer to the documentation for the variable `message-send-mail-function'
2792 to find out how to use this."
2793   ;; replace the header delimiter with a blank line
2794   (goto-char (point-min))
2795   (re-search-forward
2796    (concat "^" (regexp-quote mail-header-separator) "\n"))
2797   (replace-match "\n")
2798   (run-hooks 'message-send-mail-hook)
2799   ;; send the message
2800   (case
2801       (let ((coding-system-for-write message-send-coding-system))
2802         (apply
2803          'call-process-region 1 (point-max) message-qmail-inject-program
2804          nil nil nil
2805          ;; qmail-inject's default behaviour is to look for addresses on the
2806          ;; command line; if there're none, it scans the headers.
2807          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2808          ;;
2809          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2810          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2811          ;; message from stdin.
2812          ;;
2813          ;; qmail also has the advantage of not having been raped by
2814          ;; various vendors, so we don't have to allow for that, either --
2815          ;; compare this with message-send-mail-with-sendmail and weep
2816          ;; for sendmail's lost innocence.
2817          ;;
2818          ;; all this is way cool coz it lets us keep the arguments entirely
2819          ;; free for -inject-arguments -- a big win for the user and for us
2820          ;; since we don't have to play that double-guessing game and the user
2821          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2822          message-qmail-inject-args))
2823     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2824     ;; we have to look at the retval instead
2825     (0 nil)
2826     (100 (error "qmail-inject reported permanent failure"))
2827     (111 (error "qmail-inject reported transient failure"))
2828     ;; should never happen
2829     (t   (error "qmail-inject reported unknown failure"))))
2830
2831 (defun message-send-mail-with-mh ()
2832   "Send the prepared message buffer with mh."
2833   (let ((mh-previous-window-config nil)
2834         (name (mh-new-draft-name)))
2835     (setq buffer-file-name name)
2836     ;; MH wants to generate these headers itself.
2837     (when message-mh-deletable-headers
2838       (let ((headers message-mh-deletable-headers))
2839         (while headers
2840           (goto-char (point-min))
2841           (and (re-search-forward
2842                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2843                (message-delete-line))
2844           (pop headers))))
2845     (run-hooks 'message-send-mail-hook)
2846     ;; Pass it on to mh.
2847     (mh-send-letter)))
2848
2849 (defun message-canlock-generate ()
2850   "Return a string that is non-trival to guess.
2851 Do not use this for anything important, it is cryptographically weak."
2852   (sha1 (concat (message-unique-id)
2853                 (format "%x%x%x" (random) (random t) (random))
2854                 (prin1-to-string (recent-keys))
2855                 (prin1-to-string (garbage-collect)))))
2856
2857 (defun message-canlock-password ()
2858   "The password used by message for cancel locks.
2859 This is the value of `canlock-password', if that option is non-nil.
2860 Otherwise, generate and save a value for `canlock-password' first."
2861   (unless canlock-password
2862     (customize-save-variable 'canlock-password (message-canlock-generate)))
2863   canlock-password)
2864
2865 (defun message-insert-canlock ()
2866   (when message-insert-canlock
2867     (message-canlock-password)
2868     (canlock-insert-header)))
2869
2870 (defun message-send-news (&optional arg)
2871   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2872          (case-fold-search nil)
2873          (method (if (message-functionp message-post-method)
2874                      (funcall message-post-method arg)
2875                    message-post-method))
2876          (newsgroups-field (save-restriction
2877                             (message-narrow-to-headers-or-head)
2878                             (message-fetch-field "Newsgroups")))
2879          (followup-field (save-restriction
2880                            (message-narrow-to-headers-or-head)
2881                            (message-fetch-field "Followup-To")))
2882          ;; BUG: We really need to get the charset for each name in the
2883          ;; Newsgroups and Followup-To lines to allow crossposting
2884          ;; between group namess with incompatible character sets.
2885          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
2886          (group-field-charset
2887           (gnus-group-name-charset method newsgroups-field))
2888          (followup-field-charset 
2889           (gnus-group-name-charset method (or followup-field "")))
2890          (rfc2047-header-encoding-alist
2891           (append (when group-field-charset
2892                     (list (cons "Newsgroups" group-field-charset)))
2893                   (when followup-field-charset
2894                     (list (cons "Followup-To" followup-field-charset)))
2895                   rfc2047-header-encoding-alist))
2896          (messbuf (current-buffer))
2897          (message-syntax-checks
2898           (if (and arg
2899                    (listp message-syntax-checks))
2900               (cons '(existing-newsgroups . disabled)
2901                     message-syntax-checks)
2902             message-syntax-checks))
2903          (message-this-is-news t)
2904          (message-posting-charset
2905           (gnus-setup-posting-charset newsgroups-field))
2906          result)
2907     (if (not (message-check-news-body-syntax))
2908         nil
2909       (save-restriction
2910         (message-narrow-to-headers)
2911         ;; Insert some headers.
2912         (message-generate-headers message-required-news-headers)
2913         (message-insert-canlock)
2914         ;; Let the user do all of the above.
2915         (run-hooks 'message-header-hook))
2916       ;; Note: This check will be disabled by the ".*" default value for
2917       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
2918       (when (and group-field-charset
2919                  (listp message-syntax-checks))
2920         (setq message-syntax-checks
2921               (cons '(valid-newsgroups . disabled)
2922                     message-syntax-checks)))
2923       (message-cleanup-headers)
2924       (if (not (let ((message-post-method method))
2925                  (message-check-news-syntax)))
2926           nil
2927         (unwind-protect
2928             (save-excursion
2929               (set-buffer tembuf)
2930               (buffer-disable-undo)
2931               (erase-buffer)
2932               ;; Avoid copying text props.
2933               (insert (with-current-buffer messbuf
2934                         (buffer-substring-no-properties
2935                          (point-min) (point-max))))
2936               (message-encode-message-body)
2937               ;; Remove some headers.
2938               (save-restriction
2939                 (message-narrow-to-headers)
2940                 ;; We (re)generate the Lines header.
2941                 (when (memq 'Lines message-required-mail-headers)
2942                   (message-generate-headers '(Lines)))
2943                 ;; Remove some headers.
2944                 (message-remove-header message-ignored-news-headers t)
2945                 (let ((mail-parse-charset message-default-charset))
2946                   (mail-encode-encoded-word-buffer)))
2947               (goto-char (point-max))
2948               ;; require one newline at the end.
2949               (or (= (preceding-char) ?\n)
2950                   (insert ?\n))
2951               (let ((case-fold-search t))
2952                 ;; Remove the delimiter.
2953                 (goto-char (point-min))
2954                 (re-search-forward
2955                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2956                 (replace-match "\n")
2957                 (backward-char 1))
2958               (run-hooks 'message-send-news-hook)
2959               (gnus-open-server method)
2960               (message "Sending news with %s..." (gnus-server-string method))
2961               (setq result (let ((mail-header-separator ""))
2962                              (gnus-request-post method))))
2963           (kill-buffer tembuf))
2964         (set-buffer messbuf)
2965         (if result
2966             (push 'news message-sent-message-via)
2967           (message "Couldn't send message via news: %s"
2968                    (nnheader-get-report (car method)))
2969           nil)))))
2970
2971 ;;;
2972 ;;; Header generation & syntax checking.
2973 ;;;
2974
2975 (defun message-check-element (type)
2976   "Return non-nil if this TYPE is not to be checked."
2977   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2978       t
2979     (let ((able (assq type message-syntax-checks)))
2980       (and (consp able)
2981            (eq (cdr able) 'disabled)))))
2982
2983 (defun message-check-news-syntax ()
2984   "Check the syntax of the message."
2985   (save-excursion
2986     (save-restriction
2987       (widen)
2988       ;; We narrow to the headers and check them first.
2989       (save-excursion
2990         (save-restriction
2991           (message-narrow-to-headers)
2992           (message-check-news-header-syntax))))))
2993
2994 (defun message-check-news-header-syntax ()
2995   (and
2996    ;; Check Newsgroups header.
2997    (message-check 'newsgroups
2998      (let ((group (message-fetch-field "newsgroups")))
2999        (or
3000         (and group
3001              (not (string-match "\\`[ \t]*\\'" group)))
3002         (ignore
3003          (message
3004           "The newsgroups field is empty or missing.  Posting is denied.")))))
3005    ;; Check the Subject header.
3006    (message-check 'subject
3007      (let* ((case-fold-search t)
3008             (subject (message-fetch-field "subject")))
3009        (or
3010         (and subject
3011              (not (string-match "\\`[ \t]*\\'" subject)))
3012         (ignore
3013          (message
3014           "The subject field is empty or missing.  Posting is denied.")))))
3015    ;; Check for commands in Subject.
3016    (message-check 'subject-cmsg
3017      (if (string-match "^cmsg " (message-fetch-field "subject"))
3018          (y-or-n-p
3019           "The control code \"cmsg\" is in the subject.  Really post? ")
3020        t))
3021    ;; Check for multiple identical headers.
3022    (message-check 'multiple-headers
3023      (let (found)
3024        (while (and (not found)
3025                    (re-search-forward "^[^ \t:]+: " nil t))
3026          (save-excursion
3027            (or (re-search-forward
3028                 (concat "^"
3029                         (regexp-quote
3030                          (setq found
3031                                (buffer-substring
3032                                 (match-beginning 0) (- (match-end 0) 2))))
3033                         ":")
3034                 nil t)
3035                (setq found nil))))
3036        (if found
3037            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3038          t)))
3039    ;; Check for Version and Sendsys.
3040    (message-check 'sendsys
3041      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3042          (y-or-n-p
3043           (format "The article contains a %s command.  Really post? "
3044                   (buffer-substring (match-beginning 0)
3045                                     (1- (match-end 0)))))
3046        t))
3047    ;; See whether we can shorten Followup-To.
3048    (message-check 'shorten-followup-to
3049      (let ((newsgroups (message-fetch-field "newsgroups"))
3050            (followup-to (message-fetch-field "followup-to"))
3051            to)
3052        (when (and newsgroups
3053                   (string-match "," newsgroups)
3054                   (not followup-to)
3055                   (not
3056                    (zerop
3057                     (length
3058                      (setq to (completing-read
3059                                "Followups to: (default all groups) "
3060                                (mapcar (lambda (g) (list g))
3061                                        (cons "poster"
3062                                              (message-tokenize-header
3063                                               newsgroups)))))))))
3064          (goto-char (point-min))
3065          (insert "Followup-To: " to "\n"))
3066        t))
3067    ;; Check "Shoot me".
3068    (message-check 'shoot
3069      (if (re-search-forward
3070           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3071          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3072        t))
3073    ;; Check for Approved.
3074    (message-check 'approved
3075      (if (re-search-forward "^Approved:" nil t)
3076          (y-or-n-p "The article contains an Approved header.  Really post? ")
3077        t))
3078    ;; Check the Message-ID header.
3079    (message-check 'message-id
3080      (let* ((case-fold-search t)
3081             (message-id (message-fetch-field "message-id" t)))
3082        (or (not message-id)
3083            ;; Is there an @ in the ID?
3084            (and (string-match "@" message-id)
3085                 ;; Is there a dot in the ID?
3086                 (string-match "@[^.]*\\." message-id)
3087                 ;; Does the ID end with a dot?
3088                 (not (string-match "\\.>" message-id)))
3089            (y-or-n-p
3090             (format "The Message-ID looks strange: \"%s\".  Really post? "
3091                     message-id)))))
3092    ;; Check the Newsgroups & Followup-To headers.
3093    (message-check 'existing-newsgroups
3094      (let* ((case-fold-search t)
3095             (newsgroups (message-fetch-field "newsgroups"))
3096             (followup-to (message-fetch-field "followup-to"))
3097             (groups (message-tokenize-header
3098                      (if followup-to
3099                          (concat newsgroups "," followup-to)
3100                        newsgroups)))
3101             (post-method (if (message-functionp message-post-method)
3102                              (funcall message-post-method)
3103                            message-post-method))
3104             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3105             ;; would probably involve a new nnoo function.
3106             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3107             (method (if (and (consp post-method) 
3108                              (eq (car post-method) 'nnvirtual)
3109                              gnus-message-group-art)
3110                         (let ((group (car (nnvirtual-find-group-art
3111                                            (car gnus-message-group-art)
3112                                            (cdr gnus-message-group-art)))))
3113                           (gnus-find-method-for-group group))
3114                       post-method))
3115             (known-groups
3116              (mapcar (lambda (n)
3117                        (gnus-group-name-decode 
3118                         (gnus-group-real-name n)
3119                         (gnus-group-name-charset method n)))
3120                      (gnus-groups-from-server method)))
3121             errors)
3122        (while groups
3123          (unless (or (equal (car groups) "poster")
3124                      (member (car groups) known-groups))
3125            (push (car groups) errors))
3126          (pop groups))
3127        (cond
3128         ;; Gnus is not running.
3129         ((or (not (and (boundp 'gnus-active-hashtb)
3130                        gnus-active-hashtb))
3131              (not (boundp 'gnus-read-active-file)))
3132          t)
3133         ;; We don't have all the group names.
3134         ((and (or (not gnus-read-active-file)
3135                   (eq gnus-read-active-file 'some))
3136               errors)
3137          (y-or-n-p
3138           (format
3139            "Really post to %s possibly unknown group%s: %s? "
3140            (if (= (length errors) 1) "this" "these")
3141            (if (= (length errors) 1) "" "s")
3142            (mapconcat 'identity errors ", "))))
3143         ;; There were no errors.
3144         ((not errors)
3145          t)
3146         ;; There are unknown groups.
3147         (t
3148          (y-or-n-p
3149           (format
3150            "Really post to %s unknown group%s: %s? "
3151            (if (= (length errors) 1) "this" "these")
3152            (if (= (length errors) 1) "" "s")
3153            (mapconcat 'identity errors ", ")))))))
3154    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3155    (message-check 'valid-newsgroups
3156      (let ((case-fold-search t)
3157            (headers '("Newsgroups" "Followup-To"))
3158            header error)
3159        (while (and headers (not error))
3160          (when (setq header (mail-fetch-field (car headers)))
3161            (if (or
3162                 (not
3163                  (string-match
3164                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3165                   header))
3166                 (memq
3167                  nil (mapcar
3168                       (lambda (g)
3169                         (not (string-match "\\.\\'\\|\\.\\." g)))
3170                       (message-tokenize-header header ","))))
3171                (setq error t)))
3172          (unless error
3173            (pop headers)))
3174        (if (not error)
3175            t
3176          (y-or-n-p
3177           (format "The %s header looks odd: \"%s\".  Really post? "
3178                   (car headers) header)))))
3179    (message-check 'repeated-newsgroups
3180      (let ((case-fold-search t)
3181            (headers '("Newsgroups" "Followup-To"))
3182            header error groups group)
3183        (while (and headers
3184                    (not error))
3185          (when (setq header (mail-fetch-field (pop headers)))
3186            (setq groups (message-tokenize-header header ","))
3187            (while (setq group (pop groups))
3188              (when (member group groups)
3189                (setq error group
3190                      groups nil)))))
3191        (if (not error)
3192            t
3193          (y-or-n-p
3194           (format "Group %s is repeated in headers.  Really post? " error)))))
3195    ;; Check the From header.
3196    (message-check 'from
3197      (let* ((case-fold-search t)
3198             (from (message-fetch-field "from"))
3199             ad)
3200        (cond
3201         ((not from)
3202          (message "There is no From line.  Posting is denied.")
3203          nil)
3204         ((or (not (string-match
3205                    "@[^\\.]*\\."
3206                    (setq ad (nth 1 (mail-extract-address-components
3207                                     from))))) ;larsi@ifi
3208              (string-match "\\.\\." ad) ;larsi@ifi..uio
3209              (string-match "@\\." ad)   ;larsi@.ifi.uio
3210              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3211              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3212              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3213          (message
3214           "Denied posting -- the From looks strange: \"%s\"." from)
3215          nil)
3216         ((let ((addresses (rfc822-addresses from)))
3217            (while (and addresses
3218                        (not (eq (string-to-char (car addresses)) ?\()))
3219              (setq addresses (cdr addresses)))
3220            addresses)
3221          (message
3222           "Denied posting -- bad From address: \"%s\"." from)
3223          nil)
3224         (t t))))
3225    ;; Check the Reply-To header.
3226    (message-check 'reply-to
3227      (let* ((case-fold-search t)
3228             (reply-to (message-fetch-field "reply-to"))
3229             ad)
3230        (cond
3231         ((not reply-to)
3232          t)
3233         ((string-match "," reply-to)
3234          (y-or-n-p
3235           (format "Multiple Reply-To addresses: \"%s\". Really post? "
3236                   reply-to)))
3237         ((or (not (string-match
3238                    "@[^\\.]*\\."
3239                    (setq ad (nth 1 (mail-extract-address-components
3240                                     reply-to))))) ;larsi@ifi
3241              (string-match "\\.\\." ad) ;larsi@ifi..uio
3242              (string-match "@\\." ad)   ;larsi@.ifi.uio
3243              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3244              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3245              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
3246          (y-or-n-p
3247           (format
3248            "The Reply-To looks strange: \"%s\". Really post? "
3249            reply-to)))
3250         (t t))))))
3251
3252 (defun message-check-news-body-syntax ()
3253   (and
3254    ;; Check for long lines.
3255    (message-check 'long-lines
3256      (goto-char (point-min))
3257      (re-search-forward
3258       (concat "^" (regexp-quote mail-header-separator) "$"))
3259      (forward-line 1)
3260      (while (and
3261              (or (looking-at
3262                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
3263                  (let ((p (point)))
3264                    (end-of-line)
3265                    (< (- (point) p) 80)))
3266              (zerop (forward-line 1))))
3267      (or (bolp)
3268          (eobp)
3269          (y-or-n-p
3270           "You have lines longer than 79 characters.  Really post? ")))
3271    ;; Check whether the article is empty.
3272    (message-check 'empty
3273      (goto-char (point-min))
3274      (re-search-forward
3275       (concat "^" (regexp-quote mail-header-separator) "$"))
3276      (forward-line 1)
3277      (let ((b (point)))
3278        (goto-char (point-max))
3279        (re-search-backward message-signature-separator nil t)
3280        (beginning-of-line)
3281        (or (re-search-backward "[^ \n\t]" b t)
3282            (if (message-gnksa-enable-p 'empty-article)
3283                (y-or-n-p "Empty article.  Really post? ")
3284              (message "Denied posting -- Empty article.")
3285              nil))))
3286    ;; Check for control characters.
3287    (message-check 'control-chars
3288      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3289          (y-or-n-p
3290           "The article contains control characters.  Really post? ")
3291        t))
3292    ;; Check excessive size.
3293    (message-check 'size
3294      (if (> (buffer-size) 60000)
3295          (y-or-n-p
3296           (format "The article is %d octets long.  Really post? "
3297                   (buffer-size)))
3298        t))
3299    ;; Check whether any new text has been added.
3300    (message-check 'new-text
3301      (or
3302       (not message-checksum)
3303       (not (eq (message-checksum) message-checksum))
3304       (if (message-gnksa-enable-p 'quoted-text-only)
3305           (y-or-n-p
3306            "It looks like no new text has been added.  Really post? ")
3307         (message "Denied posting -- no new text has been added.")
3308         nil)))
3309    ;; Check the length of the signature.
3310    (message-check 'signature
3311      (goto-char (point-max))
3312      (if (> (count-lines (point) (point-max)) 5)
3313          (y-or-n-p
3314           (format
3315            "Your .sig is %d lines; it should be max 4.  Really post? "
3316            (1- (count-lines (point) (point-max)))))
3317        t))
3318    ;; Ensure that text follows last quoted portion.
3319    (message-check 'quoting-style
3320      (goto-char (point-max))
3321      (let ((no-problem t))
3322        (when (search-backward-regexp "^>[^\n]*\n" nil t)
3323          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
3324        (if no-problem
3325            t
3326          (if (message-gnksa-enable-p 'quoted-text-only)
3327              (y-or-n-p "Your text should follow quoted text.  Really post? ")
3328            ;; Ensure that
3329            (goto-char (point-min))
3330            (re-search-forward
3331             (concat "^" (regexp-quote mail-header-separator) "$"))
3332            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
3333                (y-or-n-p "Your text should follow quoted text.  Really post? ")
3334              (message "Denied posting -- only quoted text.")
3335              nil)))))))
3336
3337 (defun message-checksum ()
3338   "Return a \"checksum\" for the current buffer."
3339   (let ((sum 0))
3340     (save-excursion
3341       (goto-char (point-min))
3342       (re-search-forward
3343        (concat "^" (regexp-quote mail-header-separator) "$"))
3344       (while (not (eobp))
3345         (when (not (looking-at "[ \t\n]"))
3346           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3347                             (char-after))))
3348         (forward-char 1)))
3349     sum))
3350
3351 (defun message-do-fcc ()
3352   "Process Fcc headers in the current buffer."
3353   (let ((case-fold-search t)
3354         (buf (current-buffer))
3355         list file)
3356     (save-excursion
3357       (save-restriction
3358         (message-narrow-to-headers)
3359         (setq file (message-fetch-field "fcc" t)))
3360       (when file
3361         (set-buffer (get-buffer-create " *message temp*"))
3362         (erase-buffer)
3363         (insert-buffer-substring buf)
3364         (message-encode-message-body)
3365         (save-restriction
3366           (message-narrow-to-headers)
3367           (while (setq file (message-fetch-field "fcc" t))
3368             (push file list)
3369             (message-remove-header "fcc" nil t))
3370           (let ((mail-parse-charset message-default-charset)
3371                 (rfc2047-header-encoding-alist
3372                  (cons '("Newsgroups" . default)
3373                        rfc2047-header-encoding-alist)))
3374             (mail-encode-encoded-word-buffer)))
3375         (goto-char (point-min))
3376         (when (re-search-forward
3377                (concat "^" (regexp-quote mail-header-separator) "$")
3378                nil t)
3379           (replace-match "" t t ))
3380         ;; Process FCC operations.
3381         (while list
3382           (setq file (pop list))
3383           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3384               ;; Pipe the article to the program in question.
3385               (call-process-region (point-min) (point-max) shell-file-name
3386                                    nil nil nil shell-command-switch
3387                                    (match-string 1 file))
3388             ;; Save the article.
3389             (setq file (expand-file-name file))
3390             (unless (file-exists-p (file-name-directory file))
3391               (make-directory (file-name-directory file) t))
3392             (if (and message-fcc-handler-function
3393                      (not (eq message-fcc-handler-function 'rmail-output)))
3394                 (funcall message-fcc-handler-function file)
3395               (if (and (file-readable-p file) (mail-file-babyl-p file))
3396                   (rmail-output file 1 nil t)
3397                 (let ((mail-use-rfc822 t))
3398                   (rmail-output file 1 t t))))))
3399         (kill-buffer (current-buffer))))))
3400
3401 (defun message-output (filename)
3402   "Append this article to Unix/babyl mail file FILENAME."
3403   (if (and (file-readable-p filename)
3404            (mail-file-babyl-p filename))
3405       (gnus-output-to-rmail filename t)
3406     (gnus-output-to-mail filename t)))
3407
3408 (defun message-cleanup-headers ()
3409   "Do various automatic cleanups of the headers."
3410   ;; Remove empty lines in the header.
3411   (save-restriction
3412     (message-narrow-to-headers)
3413     ;; Remove blank lines.
3414     (while (re-search-forward "^[ \t]*\n" nil t)
3415       (replace-match "" t t))
3416
3417     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3418     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3419     ;; embedded line breaks.
3420     (goto-char (point-min))
3421     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3422       (save-restriction
3423         (narrow-to-region
3424          (point)
3425          (if (re-search-forward "^[^ \t]" nil t)
3426              (match-beginning 0)
3427            (forward-line 1)
3428            (point)))
3429         (goto-char (point-min))
3430         (while (re-search-forward "\n[ \t]+" nil t)
3431           (replace-match " " t t))     ;No line breaks (too confusing)
3432         (goto-char (point-min))
3433         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3434           (replace-match "," t t))
3435         (goto-char (point-min))
3436         ;; Remove trailing commas.
3437         (when (re-search-forward ",+$" nil t)
3438           (replace-match "" t t))))))
3439
3440 (defun message-make-date (&optional now)
3441   "Make a valid data header.
3442 If NOW, use that time instead."
3443   (let* ((now (or now (current-time)))
3444          (zone (nth 8 (decode-time now)))
3445          (sign "+"))
3446     (when (< zone 0)
3447       (setq sign "-")
3448       (setq zone (- zone)))
3449     (concat
3450      ;; The day name of the %a spec is locale-specific.  Pfff.
3451      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
3452                                              parse-time-weekdays))))
3453      (format-time-string "%d" now)
3454      ;; The month name of the %b spec is locale-specific.  Pfff.
3455      (format " %s "
3456              (capitalize (car (rassoc (nth 4 (decode-time now))
3457                                       parse-time-months))))
3458      (format-time-string "%Y %H:%M:%S " now)
3459      ;; We do all of this because XEmacs doesn't have the %z spec.
3460      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3461
3462 (defun message-make-message-id ()
3463   "Make a unique Message-ID."
3464   (concat "<" (message-unique-id)
3465           (let ((psubject (save-excursion (message-fetch-field "subject")))
3466                 (psupersedes
3467                  (save-excursion (message-fetch-field "supersedes"))))
3468             (if (or
3469                  (and message-reply-headers
3470                       (mail-header-references message-reply-headers)
3471                       (mail-header-subject message-reply-headers)
3472                       psubject
3473                       (not (string=
3474                             (message-strip-subject-re
3475                              (mail-header-subject message-reply-headers))
3476                             (message-strip-subject-re psubject))))
3477                  (and psupersedes
3478                       (string-match "_-_@" psupersedes)))
3479                 "_-_" ""))
3480           "@" (message-make-fqdn) ">"))
3481
3482 (defvar message-unique-id-char nil)
3483
3484 ;; If you ever change this function, make sure the new version
3485 ;; cannot generate IDs that the old version could.
3486 ;; You might for example insert a "." somewhere (not next to another dot
3487 ;; or string boundary), or modify the "fsf" string.
3488 (defun message-unique-id ()
3489   ;; Don't use microseconds from (current-time), they may be unsupported.
3490   ;; Instead we use this randomly inited counter.
3491   (setq message-unique-id-char
3492         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3493            ;; (current-time) returns 16-bit ints,
3494            ;; and 2^16*25 just fits into 4 digits i base 36.
3495            (* 25 25)))
3496   (let ((tm (current-time)))
3497     (concat
3498      (if (memq system-type '(ms-dos emx vax-vms))
3499          (let ((user (downcase (user-login-name))))
3500            (while (string-match "[^a-z0-9_]" user)
3501              (aset user (match-beginning 0) ?_))
3502            user)
3503        (message-number-base36 (user-uid) -1))
3504      (message-number-base36 (+ (car   tm)
3505                                (lsh (% message-unique-id-char 25) 16)) 4)
3506      (message-number-base36 (+ (nth 1 tm)
3507                                (lsh (/ message-unique-id-char 25) 16)) 4)
3508      ;; Append the newsreader name, because while the generated
3509      ;; ID is unique to this newsreader, other newsreaders might
3510      ;; otherwise generate the same ID via another algorithm.
3511      ".fsf")))
3512
3513 (defun message-number-base36 (num len)
3514   (if (if (< len 0)
3515           (<= num 0)
3516         (= len 0))
3517       ""
3518     (concat (message-number-base36 (/ num 36) (1- len))
3519             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3520                                   (% num 36))))))
3521
3522 (defun message-make-organization ()
3523   "Make an Organization header."
3524   (let* ((organization
3525           (when message-user-organization
3526             (if (message-functionp message-user-organization)
3527                 (funcall message-user-organization)
3528               message-user-organization))))
3529     (save-excursion
3530       (message-set-work-buffer)
3531       (cond ((stringp organization)
3532              (insert organization))
3533             ((and (eq t organization)
3534                   message-user-organization-file
3535                   (file-exists-p message-user-organization-file))
3536              (insert-file-contents message-user-organization-file)))
3537       (goto-char (point-min))
3538       (while (re-search-forward "[\t\n]+" nil t)
3539         (replace-match "" t t))
3540       (unless (zerop (buffer-size))
3541         (buffer-string)))))
3542
3543 (defun message-make-lines ()
3544   "Count the number of lines and return numeric string."
3545   (save-excursion
3546     (save-restriction
3547       (widen)
3548       (message-goto-body)
3549       (int-to-string (count-lines (point) (point-max))))))
3550
3551 (defun message-make-in-reply-to ()
3552   "Return the In-Reply-To header for this message."
3553   (when message-reply-headers
3554     (let ((from (mail-header-from message-reply-headers))
3555           (date (mail-header-date message-reply-headers))
3556           (msg-id (mail-header-message-id message-reply-headers)))
3557       (when from
3558         (let ((stop-pos
3559                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3560           (concat msg-id (if msg-id " (")
3561                   (if (and stop-pos
3562                            (not (zerop stop-pos)))
3563                       (substring from 0 stop-pos) from)
3564                   "'s message of \""
3565                   (if (or (not date) (string= date ""))
3566                       "(unknown date)" date)
3567                   "\"" (if msg-id ")")))))))
3568
3569 (defun message-make-distribution ()
3570   "Make a Distribution header."
3571   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3572     (cond ((message-functionp message-distribution-function)
3573            (funcall message-distribution-function))
3574           (t orig-distribution))))
3575
3576 (defun message-make-expires ()
3577   "Return an Expires header based on `message-expires'."
3578   (let ((current (current-time))
3579         (future (* 1.0 message-expires 60 60 24)))
3580     ;; Add the future to current.
3581     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3582     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3583     (message-make-date current)))
3584
3585 (defun message-make-path ()
3586   "Return uucp path."
3587   (let ((login-name (user-login-name)))
3588     (cond ((null message-user-path)
3589            (concat (system-name) "!" login-name))
3590           ((stringp message-user-path)
3591            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3592            (concat message-user-path "!" login-name))
3593           (t login-name))))
3594
3595 (defun message-make-from ()
3596   "Make a From header."
3597   (let* ((style message-from-style)
3598          (login (message-make-address))
3599          (fullname
3600           (or (and (boundp 'user-full-name)
3601                    user-full-name)
3602               (user-full-name))))
3603     (when (string= fullname "&")
3604       (setq fullname (user-login-name)))
3605     (save-excursion
3606       (message-set-work-buffer)
3607       (cond
3608        ((or (null style)
3609             (equal fullname ""))
3610         (insert login))
3611        ((or (eq style 'angles)
3612             (and (not (eq style 'parens))
3613                  ;; Use angles if no quoting is needed, or if parens would
3614                  ;; need quoting too.
3615                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3616                      (let ((tmp (concat fullname nil)))
3617                        (while (string-match "([^()]*)" tmp)
3618                          (aset tmp (match-beginning 0) ?-)
3619                          (aset tmp (1- (match-end 0)) ?-))
3620                        (string-match "[\\()]" tmp)))))
3621         (insert fullname)
3622         (goto-char (point-min))
3623         ;; Look for a character that cannot appear unquoted
3624         ;; according to RFC 822.
3625         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3626           ;; Quote fullname, escaping specials.
3627           (goto-char (point-min))
3628           (insert "\"")
3629           (while (re-search-forward "[\"\\]" nil 1)
3630             (replace-match "\\\\\\&" t))
3631           (insert "\""))
3632         (insert " <" login ">"))
3633        (t                               ; 'parens or default
3634         (insert login " (")
3635         (let ((fullname-start (point)))
3636           (insert fullname)
3637           (goto-char fullname-start)
3638           ;; RFC 822 says \ and nonmatching parentheses
3639           ;; must be escaped in comments.
3640           ;; Escape every instance of ()\ ...
3641           (while (re-search-forward "[()\\]" nil 1)
3642             (replace-match "\\\\\\&" t))
3643           ;; ... then undo escaping of matching parentheses,
3644           ;; including matching nested parentheses.
3645           (goto-char fullname-start)
3646           (while (re-search-forward
3647                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3648                   nil 1)
3649             (replace-match "\\1(\\3)" t)
3650             (goto-char fullname-start)))
3651         (insert ")")))
3652       (buffer-string))))
3653
3654 (defun message-make-sender ()
3655   "Return the \"real\" user address.
3656 This function tries to ignore all user modifications, and
3657 give as trustworthy answer as possible."
3658   (concat (user-login-name) "@" (system-name)))
3659
3660 (defun message-make-address ()
3661   "Make the address of the user."
3662   (or (message-user-mail-address)
3663       (concat (user-login-name) "@" (message-make-domain))))
3664
3665 (defun message-user-mail-address ()
3666   "Return the pertinent part of `user-mail-address'."
3667   (when user-mail-address
3668     (if (string-match " " user-mail-address)
3669         (nth 1 (mail-extract-address-components user-mail-address))
3670       user-mail-address)))
3671
3672 (defun message-make-fqdn ()
3673   "Return user's fully qualified domain name."
3674   (let ((system-name (system-name))
3675         (user-mail (message-user-mail-address)))
3676     (cond
3677      ((and (string-match "[^.]\\.[^.]" system-name)
3678            (not (string-match message-bogus-system-names system-name)))
3679       ;; `system-name' returned the right result.
3680       system-name)
3681      ;; Try `mail-host-address'.
3682      ((and (boundp 'mail-host-address)
3683            (stringp mail-host-address)
3684            (string-match "\\." mail-host-address))
3685       mail-host-address)
3686      ;; We try `user-mail-address' as a backup.
3687      ((and user-mail
3688            (string-match "\\." user-mail)
3689            (string-match "@\\(.*\\)\\'" user-mail))
3690       (match-string 1 user-mail))
3691      ;; Default to this bogus thing.
3692      (t
3693       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3694
3695 (defun message-make-host-name ()
3696   "Return the name of the host."
3697   (let ((fqdn (message-make-fqdn)))
3698     (string-match "^[^.]+\\." fqdn)
3699     (substring fqdn 0 (1- (match-end 0)))))
3700
3701 (defun message-make-domain ()
3702   "Return the domain name."
3703   (or mail-host-address
3704       (message-make-fqdn)))
3705
3706 (defun message-make-mft ()
3707   "Return the Mail-Followup-To header."
3708   (let* ((msg-recipients (message-options-get 'message-recipients))
3709          (recipients
3710           (mapcar 'mail-strip-quoted-names
3711                   (message-tokenize-header msg-recipients)))
3712          (mft-regexps (apply 'append message-subscribed-regexps
3713                              (mapcar 'regexp-quote
3714                                      message-subscribed-addresses)
3715                              (mapcar 'funcall
3716                                      message-subscribed-address-functions))))
3717     (save-match-data
3718       (when (eval (apply 'append '(or)
3719                          (mapcar
3720                           (function (lambda (regexp)
3721                                       (mapcar
3722                                        (function (lambda (recipient)
3723                                                    `(string-match ,regexp
3724                                                                   ,recipient)))
3725                                        recipients)))
3726                           mft-regexps)))
3727         msg-recipients))))
3728
3729 (defun message-generate-headers (headers)
3730   "Prepare article HEADERS.
3731 Headers already prepared in the buffer are not modified."
3732   (save-restriction
3733     (message-narrow-to-headers)
3734     (let* ((Date (message-make-date))
3735            (Message-ID (message-make-message-id))
3736            (Organization (message-make-organization))
3737            (From (message-make-from))
3738            (Path (message-make-path))
3739            (Subject nil)
3740            (Newsgroups nil)
3741            (In-Reply-To (message-make-in-reply-to))
3742            (To nil)
3743            (Distribution (message-make-distribution))
3744            (Lines (message-make-lines))
3745            (User-Agent message-newsreader)
3746            (Expires (message-make-expires))
3747            (case-fold-search t)
3748            header value elem)
3749       ;; First we remove any old generated headers.
3750       (let ((headers message-deletable-headers))
3751         (unless (buffer-modified-p)
3752           (setq headers (delq 'Message-ID (copy-sequence headers))))
3753         (while headers
3754           (goto-char (point-min))
3755           (and (re-search-forward
3756                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3757                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3758                (message-delete-line))
3759           (pop headers)))
3760       ;; Go through all the required headers and see if they are in the
3761       ;; articles already.  If they are not, or are empty, they are
3762       ;; inserted automatically - except for Subject, Newsgroups and
3763       ;; Distribution.
3764       (while headers
3765         (goto-char (point-min))
3766         (setq elem (pop headers))
3767         (if (consp elem)
3768             (if (eq (car elem) 'optional)
3769                 (setq header (cdr elem))
3770               (setq header (car elem)))
3771           (setq header elem))
3772         (when (or (not (re-search-forward
3773                         (concat "^"
3774                                 (regexp-quote
3775                                  (downcase
3776                                   (if (stringp header)
3777                                       header
3778                                     (symbol-name header))))
3779                                 ":")
3780                         nil t))
3781                   (progn
3782                     ;; The header was found.  We insert a space after the
3783                     ;; colon, if there is none.
3784                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3785                     ;; Find out whether the header is empty...
3786                     (looking-at "[ \t]*\n[^ \t]")))
3787           ;; So we find out what value we should insert.
3788           (setq value
3789                 (cond
3790                  ((and (consp elem) (eq (car elem) 'optional))
3791                   ;; This is an optional header.  If the cdr of this
3792                   ;; is something that is nil, then we do not insert
3793                   ;; this header.
3794                   (setq header (cdr elem))
3795                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3796                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3797                  ((consp elem)
3798                   ;; The element is a cons.  Either the cdr is a
3799                   ;; string to be inserted verbatim, or it is a
3800                   ;; function, and we insert the value returned from
3801                   ;; this function.
3802                   (or (and (stringp (cdr elem)) (cdr elem))
3803                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3804                  ((and (boundp header) (symbol-value header))
3805                   ;; The element is a symbol.  We insert the value
3806                   ;; of this symbol, if any.
3807                   (symbol-value header))
3808                  ((not (message-check-element header))
3809                   ;; We couldn't generate a value for this header,
3810                   ;; so we just ask the user.
3811                   (read-from-minibuffer
3812                    (format "Empty header for %s; enter value: " header)))))
3813           ;; Finally insert the header.
3814           (when (and value
3815                      (not (equal value "")))
3816             (save-excursion
3817               (if (bolp)
3818                   (progn
3819                     ;; This header didn't exist, so we insert it.
3820                     (goto-char (point-max))
3821                     (insert (if (stringp header) header (symbol-name header))
3822                             ": " value "\n")
3823                     (forward-line -1))
3824                 ;; The value of this header was empty, so we clear
3825                 ;; totally and insert the new value.
3826                 (delete-region (point) (gnus-point-at-eol))
3827                 (insert value))
3828               ;; Add the deletable property to the headers that require it.
3829               (and (memq header message-deletable-headers)
3830                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3831                    (add-text-properties
3832                     (point) (match-end 0)
3833                     '(message-deletable t face italic) (current-buffer)))))))
3834       ;; Insert new Sender if the From is strange.
3835       (let ((from (message-fetch-field "from"))
3836             (sender (message-fetch-field "sender"))
3837             (secure-sender (message-make-sender)))
3838         (when (and from
3839                    (not (message-check-element 'sender))
3840                    (not (string=
3841                          (downcase
3842                           (cadr (mail-extract-address-components from)))
3843                          (downcase secure-sender)))
3844                    (or (null sender)
3845                        (not
3846                         (string=
3847                          (downcase
3848                           (cadr (mail-extract-address-components sender)))
3849                          (downcase secure-sender)))))
3850           (goto-char (point-min))
3851           ;; Rename any old Sender headers to Original-Sender.
3852           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3853             (beginning-of-line)
3854             (insert "Original-")
3855             (beginning-of-line))
3856           (when (or (message-news-p)
3857                     (string-match "@.+\\.." secure-sender))
3858             (insert "Sender: " secure-sender "\n")))))))
3859
3860 (defun message-insert-courtesy-copy ()
3861   "Insert a courtesy message in mail copies of combined messages."
3862   (let (newsgroups)
3863     (save-excursion
3864       (save-restriction
3865         (message-narrow-to-headers)
3866         (when (setq newsgroups (message-fetch-field "newsgroups"))
3867           (goto-char (point-max))
3868           (insert "Posted-To: " newsgroups "\n")))
3869       (forward-line 1)
3870       (when message-courtesy-message
3871         (cond
3872          ((string-match "%s" message-courtesy-message)
3873           (insert (format message-courtesy-message newsgroups)))
3874          (t
3875           (insert message-courtesy-message)))))))
3876
3877 ;;;
3878 ;;; Setting up a message buffer
3879 ;;;
3880
3881 (defun message-fill-address (header value)
3882   (save-restriction
3883     (narrow-to-region (point) (point))
3884     (insert (capitalize (symbol-name header))
3885             ": "
3886             (if (consp value) (car value) value)
3887             "\n")
3888     (narrow-to-region (point-min) (1- (point-max)))
3889     (let (quoted last)
3890       (goto-char (point-min))
3891       (while (not (eobp))
3892         (skip-chars-forward "^,\"" (point-max))
3893         (if (or (eq (char-after) ?,)
3894                 (eobp))
3895             (when (not quoted)
3896               (if (and (> (current-column) 78)
3897                        last)
3898                   (progn
3899                     (save-excursion
3900                       (goto-char last)
3901                       (insert "\n\t"))
3902                     (setq last (1+ (point))))
3903                 (setq last (1+ (point)))))
3904           (setq quoted (not quoted)))
3905         (unless (eobp)
3906           (forward-char 1))))
3907     (goto-char (point-max))
3908     (widen)
3909     (forward-line 1)))
3910
3911 (defun message-fill-header (header value)
3912   (let ((begin (point))
3913         (fill-column 78)
3914         (fill-prefix "\t"))
3915     (insert (capitalize (symbol-name header))
3916             ": "
3917             (if (consp value) (car value) value)
3918             "\n")
3919     (save-restriction
3920       (narrow-to-region begin (point))
3921       (fill-region-as-paragraph begin (point))
3922       ;; Tapdance around looong Message-IDs.
3923       (forward-line -1)
3924       (when (looking-at "[ \t]*$")
3925         (message-delete-line))
3926       (goto-char begin)
3927       (re-search-forward ":" nil t)
3928       (when (looking-at "\n[ \t]+")
3929         (replace-match " " t t))
3930       (goto-char (point-max)))))
3931
3932 (defun message-shorten-1 (list cut surplus)
3933   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
3934   (setcdr (nthcdr (- cut 2) list)
3935           (nthcdr (+ (- cut 2) surplus 1) list)))
3936
3937 (defun message-shorten-references (header references)
3938   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
3939 If folding is disallowed, also check that the REFERENCES are less
3940 than 988 characters long, and if they are not, trim them until they are."
3941   (let ((maxcount 21)
3942         (count 0)
3943         (cut 2)
3944         refs)
3945     (with-temp-buffer
3946       (insert references)
3947       (goto-char (point-min))
3948       ;; Cons a list of valid references.
3949       (while (re-search-forward "<[^>]+>" nil t)
3950         (push (match-string 0) refs))
3951       (setq refs (nreverse refs)
3952             count (length refs)))
3953
3954     ;; If the list has more than MAXCOUNT elements, trim it by
3955     ;; removing the CUTth element and the required number of
3956     ;; elements that follow.
3957     (when (> count maxcount)
3958       (let ((surplus (- count maxcount)))
3959         (message-shorten-1 refs cut surplus)
3960         (decf count surplus)))
3961
3962     ;; If folding is disallowed, make sure the total length (including
3963     ;; the spaces between) will be less than MAXSIZE characters.
3964     ;;
3965     ;; Only disallow folding for News messages. At this point the headers
3966     ;; have not been generated, thus we use message-this-is-news directly.
3967     (when (and message-this-is-news message-cater-to-broken-inn)
3968       (let ((maxsize 988)
3969             (totalsize (+ (apply #'+ (mapcar #'length refs))
3970                           (1- count)))
3971             (surplus 0)
3972             (ptr (nthcdr (1- cut) refs)))
3973         ;; Decide how many elements to cut off...
3974         (while (> totalsize maxsize)
3975           (decf totalsize (1+ (length (car ptr))))
3976           (incf surplus)
3977           (setq ptr (cdr ptr)))
3978         ;; ...and do it.
3979         (when (> surplus 0)
3980           (message-shorten-1 refs cut surplus))))
3981
3982     ;; Finally, collect the references back into a string and insert
3983     ;; it into the buffer.
3984     (let ((refstring (mapconcat #'identity refs " ")))
3985       (if (and message-this-is-news message-cater-to-broken-inn)
3986           (insert (capitalize (symbol-name header)) ": "
3987                   refstring "\n")
3988         (message-fill-header header refstring)))))
3989
3990 (defun message-position-point ()
3991   "Move point to where the user probably wants to find it."
3992   (message-narrow-to-headers)
3993   (cond
3994    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3995     (search-backward ":" )
3996     (widen)
3997     (forward-char 1)
3998     (if (eq (char-after) ? )
3999         (forward-char 1)
4000       (insert " ")))
4001    (t
4002     (goto-char (point-max))
4003     (widen)
4004     (forward-line 1)
4005     (unless (looking-at "$")
4006       (forward-line 2)))
4007    (sit-for 0)))
4008
4009 (defun message-beginning-of-line (&optional n)
4010   "Move point to beginning of header value or to beginning of line."
4011   (interactive "p")
4012   (if (message-point-in-header-p)
4013       (let* ((here (point))
4014              (bol (progn (beginning-of-line n) (point)))
4015              (eol (gnus-point-at-eol))
4016              (eoh (re-search-forward ": *" eol t)))
4017         (if (or (not eoh) (equal here eoh))
4018             (goto-char bol)
4019           (goto-char eoh)))
4020     (beginning-of-line n)))
4021
4022 (defun message-buffer-name (type &optional to group)
4023   "Return a new (unique) buffer name based on TYPE and TO."
4024   (cond
4025    ;; Generate a new buffer name The Message Way.
4026    ((eq message-generate-new-buffers 'unique)
4027     (generate-new-buffer-name
4028      (concat "*" type
4029              (if to
4030                  (concat " to "
4031                          (or (car (mail-extract-address-components to))
4032                              to) "")
4033                "")
4034              (if (and group (not (string= group ""))) (concat " on " group) "")
4035              "*")))
4036    ;; Check whether `message-generate-new-buffers' is a function,
4037    ;; and if so, call it.
4038    ((message-functionp message-generate-new-buffers)
4039     (funcall message-generate-new-buffers type to group))
4040    ((eq message-generate-new-buffers 'unsent)
4041     (generate-new-buffer-name
4042      (concat "*unsent " type
4043              (if to
4044                  (concat " to "
4045                          (or (car (mail-extract-address-components to))
4046                              to) "")
4047                "")
4048              (if (and group (not (string= group ""))) (concat " on " group) "")
4049              "*")))
4050    ;; Use standard name.
4051    (t
4052     (format "*%s message*" type))))
4053
4054 (defun message-pop-to-buffer (name)
4055   "Pop to buffer NAME, and warn if it already exists and is modified."
4056   (let ((buffer (get-buffer name)))
4057     (if (and buffer
4058              (buffer-name buffer))
4059         (progn
4060           (set-buffer (pop-to-buffer buffer))
4061           (when (and (buffer-modified-p)
4062                      (not (y-or-n-p
4063                            "Message already being composed; erase? ")))
4064             (error "Message being composed")))
4065       (set-buffer (pop-to-buffer name)))
4066     (erase-buffer)
4067     (message-mode)))
4068
4069 (defun message-do-send-housekeeping ()
4070   "Kill old message buffers."
4071   ;; We might have sent this buffer already.  Delete it from the
4072   ;; list of buffers.
4073   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4074   (while (and message-max-buffers
4075               message-buffer-list
4076               (>= (length message-buffer-list) message-max-buffers))
4077     ;; Kill the oldest buffer -- unless it has been changed.
4078     (let ((buffer (pop message-buffer-list)))
4079       (when (and (buffer-name buffer)
4080                  (not (buffer-modified-p buffer)))
4081         (kill-buffer buffer))))
4082   ;; Rename the buffer.
4083   (if message-send-rename-function
4084       (funcall message-send-rename-function)
4085     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
4086     (when (string-match
4087            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
4088            (buffer-name))
4089       (let ((name (match-string 2 (buffer-name)))
4090             to group)
4091         (if (not (or (null name)
4092                      (string-equal name "mail")
4093                      (string-equal name "news")))
4094             (setq name (concat "*sent " name "*"))
4095           (message-narrow-to-headers)
4096           (setq to (message-fetch-field "to"))
4097           (setq group (message-fetch-field "newsgroups"))
4098           (widen)
4099           (setq name
4100                 (cond
4101                  (to (concat "*sent mail to "
4102                              (or (car (mail-extract-address-components to))
4103                                  to) "*"))
4104                  ((and group (not (string= group "")))
4105                   (concat "*sent news on " group "*"))
4106                  (t "*sent mail*"))))
4107         (unless (string-equal name (buffer-name))
4108           (rename-buffer name t)))))
4109   ;; Push the current buffer onto the list.
4110   (when message-max-buffers
4111     (setq message-buffer-list
4112           (nconc message-buffer-list (list (current-buffer))))))
4113
4114 (defun message-mail-user-agent ()
4115   (let ((mua (cond
4116               ((not message-mail-user-agent) nil)
4117               ((eq message-mail-user-agent t) mail-user-agent)
4118               (t message-mail-user-agent))))
4119     (if (memq mua '(message-user-agent gnus-user-agent))
4120         nil
4121       mua)))
4122
4123 (defun message-setup (headers &optional replybuffer actions switch-function)
4124   (let ((mua (message-mail-user-agent))
4125         subject to field yank-action)
4126     (if (not (and message-this-is-mail mua))
4127         (message-setup-1 headers replybuffer actions)
4128       (if replybuffer
4129           (setq yank-action (list 'insert-buffer replybuffer)))
4130       (setq headers (copy-sequence headers))
4131       (setq field (assq 'Subject headers))
4132       (when field
4133         (setq subject (cdr field))
4134         (setq headers (delq field headers)))
4135       (setq field (assq 'To headers))
4136       (when field
4137         (setq to (cdr field))
4138         (setq headers (delq field headers)))
4139       (let ((mail-user-agent mua))
4140         (compose-mail to subject
4141                       (mapcar (lambda (item)
4142                                 (cons
4143                                  (format "%s" (car item))
4144                                  (cdr item)))
4145                               headers)
4146                       nil switch-function yank-action actions)))))
4147
4148 ;;;(defvar mc-modes-alist)
4149 (defun message-setup-1 (headers &optional replybuffer actions)
4150 ;;;   (when (and (boundp 'mc-modes-alist)
4151 ;;;          (not (assq 'message-mode mc-modes-alist)))
4152 ;;;     (push '(message-mode (encrypt . mc-encrypt-message)
4153 ;;;                      (sign . mc-sign-message))
4154 ;;;       mc-modes-alist))
4155   (dolist (action actions)
4156     (condition-case nil
4157         (add-to-list 'message-send-actions
4158                      `(apply ',(car action) ',(cdr action)))))
4159   (setq message-reply-buffer replybuffer)
4160   (goto-char (point-min))
4161   ;; Insert all the headers.
4162   (mail-header-format
4163    (let ((h headers)
4164          (alist message-header-format-alist))
4165      (while h
4166        (unless (assq (caar h) message-header-format-alist)
4167          (push (list (caar h)) alist))
4168        (pop h))
4169      alist)
4170    headers)
4171   (delete-region (point) (progn (forward-line -1) (point)))
4172   (when message-default-headers
4173     (insert message-default-headers)
4174     (or (bolp) (insert ?\n)))
4175   (put-text-property
4176    (point)
4177    (progn
4178      (insert mail-header-separator "\n")
4179      (1- (point)))
4180    'read-only nil)
4181   (forward-line -1)
4182   (when (message-news-p)
4183     (when message-default-news-headers
4184       (insert message-default-news-headers)
4185       (or (bolp) (insert ?\n)))
4186     (when message-generate-headers-first
4187       (message-generate-headers
4188        (delq 'Lines
4189              (delq 'Subject
4190                    (copy-sequence message-required-news-headers))))))
4191   (when (message-mail-p)
4192     (when message-default-mail-headers
4193       (insert message-default-mail-headers)
4194       (or (bolp) (insert ?\n)))
4195     (when message-generate-headers-first
4196       (message-generate-headers
4197        (delq 'Lines
4198              (delq 'Subject
4199                    (copy-sequence message-required-mail-headers))))))
4200   (run-hooks 'message-signature-setup-hook)
4201   (message-insert-signature)
4202   (save-restriction
4203     (message-narrow-to-headers)
4204     (if message-alternative-emails
4205         (message-use-alternative-email-as-from))
4206     (run-hooks 'message-header-setup-hook))
4207   (set-buffer-modified-p nil)
4208   (setq buffer-undo-list nil)
4209   (run-hooks 'message-setup-hook)
4210   (message-position-point)
4211   (undo-boundary))
4212
4213 (defun message-set-auto-save-file-name ()
4214   "Associate the message buffer with a file in the drafts directory."
4215   (when message-auto-save-directory
4216     (unless (file-directory-p
4217              (directory-file-name message-auto-save-directory))
4218       (gnus-make-directory message-auto-save-directory))
4219     (if (gnus-alive-p)
4220         (setq message-draft-article
4221               (nndraft-request-associate-buffer "drafts"))
4222       (setq buffer-file-name (expand-file-name
4223                               (if (memq system-type 
4224                                         '(ms-dos ms-windows windows-nt 
4225                                                  cygwin32 win32 w32 
4226                                                  mswindows))
4227                                   "message"
4228                                 "*message*")
4229                               message-auto-save-directory))
4230       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4231     (clear-visited-file-modtime)
4232     (setq buffer-file-coding-system message-draft-coding-system)))
4233
4234 (defun message-disassociate-draft ()
4235   "Disassociate the message buffer from the drafts directory."
4236   (when message-draft-article
4237     (nndraft-request-expire-articles
4238      (list message-draft-article) "drafts" nil t)))
4239
4240 (defun message-insert-headers ()
4241   "Generate the headers for the article."
4242   (interactive)
4243   (save-excursion
4244     (save-restriction
4245       (message-narrow-to-headers)
4246       (when (message-news-p)
4247         (message-generate-headers
4248          (delq 'Lines
4249                (delq 'Subject
4250                      (copy-sequence message-required-news-headers)))))
4251       (when (message-mail-p)
4252         (message-generate-headers
4253          (delq 'Lines
4254                (delq 'Subject
4255                      (copy-sequence message-required-mail-headers))))))))
4256
4257 \f
4258
4259 ;;;
4260 ;;; Commands for interfacing with message
4261 ;;;
4262
4263 ;;;###autoload
4264 (defun message-mail (&optional to subject
4265                                other-headers continue switch-function
4266                                yank-action send-actions)
4267   "Start editing a mail message to be sent.
4268 OTHER-HEADERS is an alist of header/value pairs."
4269   (interactive)
4270   (let ((message-this-is-mail t) replybuffer)
4271     (unless (message-mail-user-agent)
4272       (message-pop-to-buffer (message-buffer-name "mail" to)))
4273     ;; FIXME: message-mail should do something if YANK-ACTION is not
4274     ;; insert-buffer.
4275     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
4276          (setq replybuffer (nth 1 yank-action)))
4277     (message-setup
4278      (nconc
4279       `((To . ,(or to "")) (Subject . ,(or subject "")))
4280       (when other-headers other-headers))
4281      replybuffer send-actions)
4282     ;; FIXME: Should return nil if failure.
4283     t))
4284
4285 ;;;###autoload
4286 (defun message-news (&optional newsgroups subject)
4287   "Start editing a news article to be sent."
4288   (interactive)
4289   (let ((message-this-is-news t))
4290     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
4291     (message-setup `((Newsgroups . ,(or newsgroups ""))
4292                      (Subject . ,(or subject ""))))))
4293
4294 (defun message-get-reply-headers (wide &optional to-address)
4295   (let (follow-to mct never-mct to cc author mft recipients)
4296     ;; Find all relevant headers we need.
4297     (setq to (message-fetch-field "to")
4298           cc (message-fetch-field "cc")
4299           mct (message-fetch-field "mail-copies-to")
4300           author (or (message-fetch-field "mail-reply-to")
4301                      (message-fetch-field "reply-to")
4302                      (message-fetch-field "from")
4303                      "")
4304           mft (and message-use-mail-followup-to
4305                    (message-fetch-field "mail-followup-to")))
4306
4307     ;; Handle special values of Mail-Copies-To.
4308     (when mct
4309       (cond ((or (equal (downcase mct) "never")
4310                  (equal (downcase mct) "nobody"))
4311              (setq never-mct t)
4312              (setq mct nil))
4313             ((or (equal (downcase mct) "always")
4314                  (equal (downcase mct) "poster"))
4315              (setq mct author))))
4316
4317     (save-match-data
4318       ;; Build (textual) list of new recipient addresses.
4319       (cond
4320        ((not wide)
4321         (setq recipients (concat ", " author)))
4322        ((and mft
4323              (string-match "[^ \t,]" mft)
4324              (or (not (eq message-use-mail-followup-to 'ask))
4325                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
4326 You should normally obey the Mail-Followup-To: header.  In this
4327 article, it has the value of
4328
4329 " mft "
4330
4331 which directs your response to " (if (string-match "," mft)
4332                                      "the specified addresses"
4333                                    "that address only") ".
4334
4335 Most commonly, Mail-Followup-To is used by a mailing list poster to
4336 express that responses should be sent to just the list, and not the
4337 poster as well.
4338
4339 If a message is posted to several mailing lists, Mail-Followup-To may
4340 also be used to direct the following discussion to one list only,
4341 because discussions that are spread over several lists tend to be
4342 fragmented and very difficult to follow.
4343
4344 Also, some source/announcement lists are not intended for discussion;
4345 responses here are directed to other addresses.")))
4346         (setq recipients (concat ", " mft)))
4347        (to-address
4348         (setq recipients (concat ", " to-address))
4349         ;; If the author explicitly asked for a copy, we don't deny it to them.
4350         (if mct (setq recipients (concat recipients ", " mct))))
4351        (t
4352         (setq recipients (if never-mct "" (concat ", " author)))
4353         (if to  (setq recipients (concat recipients ", " to)))
4354         (if cc  (setq recipients (concat recipients ", " cc)))
4355         (if mct (setq recipients (concat recipients ", " mct)))))
4356       (if (>= (length recipients) 2)
4357           ;; Strip the leading ", ".
4358           (setq recipients (substring recipients 2)))
4359       ;; Squeeze whitespace.
4360       (while (string-match "[ \t][ \t]+" recipients)
4361         (setq recipients (replace-match " " t t recipients)))
4362       ;; Remove addresses that match `rmail-dont-reply-to-names'.
4363       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4364         (setq recipients (rmail-dont-reply-to recipients)))
4365       ;; Perhaps "Mail-Copies-To: never" removed the only address?
4366       (if (string-equal recipients "")
4367           (setq recipients author))
4368       ;; Convert string to a list of (("foo@bar" . "Name <foo@bar>") ...).
4369       (setq recipients
4370             (mapcar
4371              (lambda (addr)
4372                (cons (mail-strip-quoted-names addr) addr))
4373              (message-tokenize-header recipients)))
4374       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
4375       (let ((s recipients))
4376         (while s
4377           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
4378       ;; Build the header alist.  Allow the user to be asked whether
4379       ;; or not to reply to all recipients in a wide reply.
4380       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
4381       (when (and recipients
4382                  (or (not message-wide-reply-confirm-recipients)
4383                      (y-or-n-p "Reply to all recipients? ")))
4384         (setq recipients (mapconcat
4385                           (lambda (addr) (cdr addr)) recipients ", "))
4386         (if (string-match "^ +" recipients)
4387             (setq recipients (substring recipients (match-end 0))))
4388         (push (cons 'Cc recipients) follow-to)))
4389     follow-to))
4390
4391 ;;;###autoload
4392 (defun message-reply (&optional to-address wide)
4393   "Start editing a reply to the article in the current buffer."
4394   (interactive)
4395   (require 'gnus-sum)                   ; for gnus-list-identifiers
4396   (let ((cur (current-buffer))
4397         from subject date reply-to to cc
4398         references message-id follow-to
4399         (inhibit-point-motion-hooks t)
4400         (message-this-is-mail t)
4401         gnus-warning)
4402     (save-restriction
4403       (message-narrow-to-head-1)
4404       ;; Allow customizations to have their say.
4405       (if (not wide)
4406           ;; This is a regular reply.
4407           (when (message-functionp message-reply-to-function)
4408             (save-excursion
4409               (setq follow-to (funcall message-reply-to-function))))
4410         ;; This is a followup.
4411         (when (message-functionp message-wide-reply-to-function)
4412           (save-excursion
4413             (setq follow-to
4414                   (funcall message-wide-reply-to-function)))))
4415       (setq message-id (message-fetch-field "message-id" t)
4416             references (message-fetch-field "references")
4417             date (message-fetch-field "date")
4418             from (message-fetch-field "from")
4419             subject (or (message-fetch-field "subject") "none"))
4420       (when gnus-list-identifiers
4421         (setq subject (message-strip-list-identifiers subject)))
4422       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4423
4424       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4425                  (string-match "<[^>]+>" gnus-warning))
4426         (setq message-id (match-string 0 gnus-warning)))
4427
4428       (unless follow-to
4429         (setq follow-to (message-get-reply-headers wide to-address))))
4430
4431     (unless (message-mail-user-agent)
4432       (message-pop-to-buffer
4433        (message-buffer-name
4434         (if wide "wide reply" "reply") from
4435         (if wide to-address nil))))
4436
4437     (setq message-reply-headers
4438           (vector 0 subject from date message-id references 0 0 ""))
4439
4440     (message-setup
4441      `((Subject . ,subject)
4442        ,@follow-to
4443        ,@(if (or references message-id)
4444              `((References . ,(concat (or references "") (and references " ")
4445                                       (or message-id ""))))
4446            nil))
4447      cur)))
4448
4449 ;;;###autoload
4450 (defun message-wide-reply (&optional to-address)
4451   "Make a \"wide\" reply to the message in the current buffer."
4452   (interactive)
4453   (message-reply to-address t))
4454
4455 ;;;###autoload
4456 (defun message-followup (&optional to-newsgroups)
4457   "Follow up to the message in the current buffer.
4458 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4459   (interactive)
4460   (require 'gnus-sum)                   ; for gnus-list-identifiers
4461   (let ((cur (current-buffer))
4462         from subject date reply-to mrt mct
4463         references message-id follow-to
4464         (inhibit-point-motion-hooks t)
4465         (message-this-is-news t)
4466         followup-to distribution newsgroups gnus-warning posted-to)
4467     (save-restriction
4468       (narrow-to-region
4469        (goto-char (point-min))
4470        (if (search-forward "\n\n" nil t)
4471            (1- (point))
4472          (point-max)))
4473       (when (message-functionp message-followup-to-function)
4474         (setq follow-to
4475               (funcall message-followup-to-function)))
4476       (setq from (message-fetch-field "from")
4477             date (message-fetch-field "date")
4478             subject (or (message-fetch-field "subject") "none")
4479             references (message-fetch-field "references")
4480             message-id (message-fetch-field "message-id" t)
4481             followup-to (message-fetch-field "followup-to")
4482             newsgroups (message-fetch-field "newsgroups")
4483             posted-to (message-fetch-field "posted-to")
4484             reply-to (message-fetch-field "reply-to")
4485             mrt (message-fetch-field "mail-reply-to")
4486             distribution (message-fetch-field "distribution")
4487             mct (message-fetch-field "mail-copies-to"))
4488       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4489                  (string-match "<[^>]+>" gnus-warning))
4490         (setq message-id (match-string 0 gnus-warning)))
4491       ;; Remove bogus distribution.
4492       (when (and (stringp distribution)
4493                  (let ((case-fold-search t))
4494                    (string-match "world" distribution)))
4495         (setq distribution nil))
4496       (if gnus-list-identifiers
4497           (setq subject (message-strip-list-identifiers subject)))
4498       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4499       (widen))
4500
4501     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4502
4503     (message-setup
4504      `((Subject . ,subject)
4505        ,@(cond
4506           (to-newsgroups
4507            (list (cons 'Newsgroups to-newsgroups)))
4508           (follow-to follow-to)
4509           ((and followup-to message-use-followup-to)
4510            (list
4511             (cond
4512              ((equal (downcase followup-to) "poster")
4513               (if (or (eq message-use-followup-to 'use)
4514                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
4515 You should normally obey the Followup-To: header.
4516
4517 `Followup-To: poster' sends your response via e-mail instead of news.
4518
4519 A typical situation where `Followup-To: poster' is used is when the poster
4520 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4521                   (progn
4522                     (setq message-this-is-news nil)
4523                     (cons 'To (or mrt reply-to from "")))
4524                 (cons 'Newsgroups newsgroups)))
4525              (t
4526               (if (or (equal followup-to newsgroups)
4527                       (not (eq message-use-followup-to 'ask))
4528                       (message-y-or-n-p
4529                        (concat "Obey Followup-To: " followup-to "? ") t "\
4530 You should normally obey the Followup-To: header.
4531
4532         `Followup-To: " followup-to "'
4533 directs your response to " (if (string-match "," followup-to)
4534                                "the specified newsgroups"
4535                              "that newsgroup only") ".
4536
4537 If a message is posted to several newsgroups, Followup-To is often
4538 used to direct the following discussion to one newsgroup only,
4539 because discussions that are spread over several newsgroup tend to
4540 be fragmented and very difficult to follow.
4541
4542 Also, some source/announcement newsgroups are not intended for discussion;
4543 responses here are directed to other newsgroups."))
4544                   (cons 'Newsgroups followup-to)
4545                 (cons 'Newsgroups newsgroups))))))
4546           (posted-to
4547            `((Newsgroups . ,posted-to)))
4548           (t
4549            `((Newsgroups . ,newsgroups))))
4550        ,@(and distribution (list (cons 'Distribution distribution)))
4551        ,@(if (or references message-id)
4552              `((References . ,(concat (or references "") (and references " ")
4553                                       (or message-id "")))))
4554        ,@(when (and mct
4555                     (not (or (equal (downcase mct) "never")
4556                              (equal (downcase mct) "nobody"))))
4557            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4558                                    (equal (downcase mct) "poster"))
4559                                (or mrt reply-to from "")
4560                              mct)))))
4561
4562      cur)
4563
4564     (setq message-reply-headers
4565           (vector 0 subject from date message-id references 0 0 ""))))
4566
4567
4568 ;;;###autoload
4569 (defun message-cancel-news (&optional arg)
4570   "Cancel an article you posted.
4571 If ARG, allow editing of the cancellation message."
4572   (interactive "P")
4573   (unless (message-news-p)
4574     (error "This is not a news article; canceling is impossible"))
4575   (let (from newsgroups message-id distribution buf sender)
4576     (save-excursion
4577       ;; Get header info from original article.
4578       (save-restriction
4579         (message-narrow-to-head-1)
4580         (setq from (message-fetch-field "from")
4581               sender (message-fetch-field "sender")
4582               newsgroups (message-fetch-field "newsgroups")
4583               message-id (message-fetch-field "message-id" t)
4584               distribution (message-fetch-field "distribution")))
4585       ;; Make sure that this article was written by the user.
4586       (unless (or
4587                ;; Canlock-logic as suggested by Per Abrahamsen
4588                ;; <abraham@dina.kvl.dk>
4589                ;;
4590                ;; IF article has cancel-lock THEN
4591                ;;   IF we can verify it THEN
4592                ;;     issue cancel
4593                ;;   ELSE
4594                ;;     error: cancellock: article is not yours
4595                ;; ELSE
4596                ;;   Use old rules, comparing sender...
4597                (if (message-fetch-field "Cancel-Lock")
4598                    (if (null (canlock-verify))
4599                        t
4600                      (error "Failed to verify Cancel-lock: This article is not yours"))
4601                  nil)
4602                (message-gnksa-enable-p 'cancel-messages)
4603                (and sender
4604                     (string-equal
4605                      (downcase sender)
4606                      (downcase (message-make-sender))))
4607                (string-equal
4608                 (downcase (cadr (mail-extract-address-components from)))
4609                 (downcase (cadr (mail-extract-address-components
4610                                  (message-make-from))))))
4611         (error "This article is not yours"))
4612       (when (yes-or-no-p "Do you really want to cancel this article? ")
4613         ;; Make control message.
4614         (if arg
4615             (message-news)
4616           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4617         (erase-buffer)
4618         (insert "Newsgroups: " newsgroups "\n"
4619                 "From: " from "\n"
4620                 "Subject: cmsg cancel " message-id "\n"
4621                 "Control: cancel " message-id "\n"
4622                 (if distribution
4623                     (concat "Distribution: " distribution "\n")
4624                   "")
4625                 mail-header-separator "\n"
4626                 message-cancel-message)
4627         (run-hooks 'message-cancel-hook)
4628         (unless arg
4629           (message "Canceling your article...")
4630           (if (let ((message-syntax-checks
4631                      'dont-check-for-anything-just-trust-me))
4632                 (funcall message-send-news-function))
4633               (message "Canceling your article...done"))
4634           (kill-buffer buf))))))
4635
4636 ;;;###autoload
4637 (defun message-supersede ()
4638   "Start composing a message to supersede the current message.
4639 This is done simply by taking the old article and adding a Supersedes
4640 header line with the old Message-ID."
4641   (interactive)
4642   (let ((cur (current-buffer))
4643         (sender (message-fetch-field "sender"))
4644         (from (message-fetch-field "from")))
4645     ;; Check whether the user owns the article that is to be superseded.
4646     (unless (or
4647              ;; Canlock-logic as suggested by Per Abrahamsen
4648              ;; <abraham@dina.kvl.dk>
4649              ;;
4650              ;; IF article has cancel-lock THEN
4651              ;;   IF we can verify it THEN
4652              ;;     issue cancel
4653              ;;   ELSE
4654              ;;     error: cancellock: article is not yours
4655              ;; ELSE
4656              ;;   Use old rules, comparing sender...
4657              (if (message-fetch-field "Cancel-Lock")
4658                  (if (null (canlock-verify))
4659                      t
4660                    (error "Failed to verify Cancel-lock: This article is not yours"))
4661                nil)
4662              (message-gnksa-enable-p 'cancel-messages)
4663                 (and sender
4664                      (string-equal
4665                       (downcase sender)
4666                       (downcase (message-make-sender))))
4667                 (string-equal
4668                  (downcase (cadr (mail-extract-address-components from)))
4669                  (downcase (cadr (mail-extract-address-components
4670                                   (message-make-from))))))
4671       (error "This article is not yours"))
4672     ;; Get a normal message buffer.
4673     (message-pop-to-buffer (message-buffer-name "supersede"))
4674     (insert-buffer-substring cur)
4675     (mime-to-mml)
4676     (message-narrow-to-head-1)
4677     ;; Remove unwanted headers.
4678     (when message-ignored-supersedes-headers
4679       (message-remove-header message-ignored-supersedes-headers t))
4680     (goto-char (point-min))
4681     (if (not (re-search-forward "^Message-ID: " nil t))
4682         (error "No Message-ID in this article")
4683       (replace-match "Supersedes: " t t))
4684     (goto-char (point-max))
4685     (insert mail-header-separator)
4686     (widen)
4687     (forward-line 1)))
4688
4689 ;;;###autoload
4690 (defun message-recover ()
4691   "Reread contents of current buffer from its last auto-save file."
4692   (interactive)
4693   (let ((file-name (make-auto-save-file-name)))
4694     (cond ((save-window-excursion
4695              (if (not (eq system-type 'vax-vms))
4696                  (with-output-to-temp-buffer "*Directory*"
4697                    (with-current-buffer standard-output
4698                      (fundamental-mode)) ; for Emacs 20.4+
4699                    (buffer-disable-undo standard-output)
4700                    (let ((default-directory "/"))
4701                      (call-process
4702                       "ls" nil standard-output nil "-l" file-name))))
4703              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4704            (let ((buffer-read-only nil))
4705              (erase-buffer)
4706              (insert-file-contents file-name nil)))
4707           (t (error "message-recover cancelled")))))
4708
4709 ;;; Washing Subject:
4710
4711 (defun message-wash-subject (subject)
4712   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
4713 Previous forwarders, replyers, etc. may add it."
4714   (with-temp-buffer
4715     (insert-string subject)
4716     (goto-char (point-min))
4717     ;; strip Re/Fwd stuff off the beginning
4718     (while (re-search-forward
4719             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4720       (replace-match ""))
4721
4722     ;; and gnus-style forwards [foo@bar.com] subject
4723     (goto-char (point-min))
4724     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4725       (replace-match ""))
4726
4727     ;; and off the end
4728     (goto-char (point-max))
4729     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4730       (replace-match ""))
4731
4732     ;; and finally, any whitespace that was left-over
4733     (goto-char (point-min))
4734     (while (re-search-forward "^[ \t]+" nil t)
4735       (replace-match ""))
4736     (goto-char (point-max))
4737     (while (re-search-backward "[ \t]+$" nil t)
4738       (replace-match ""))
4739
4740     (buffer-string)))
4741
4742 ;;; Forwarding messages.
4743
4744 (defvar message-forward-decoded-p nil
4745   "Non-nil means the original message is decoded.")
4746
4747 (defun message-forward-subject-author-subject (subject)
4748   "Generate a SUBJECT for a forwarded message.
4749 The form is: [Source] Subject, where if the original message was mail,
4750 Source is the sender, and if the original message was news, Source is
4751 the list of newsgroups is was posted to."
4752   (concat "["
4753           (let ((prefix
4754                  (or (message-fetch-field "newsgroups")
4755                      (message-fetch-field "from")
4756                      "(nowhere)")))
4757             (if message-forward-decoded-p
4758                 prefix
4759               (mail-decode-encoded-word-string prefix)))
4760           "] " subject))
4761
4762 (defun message-forward-subject-fwd (subject)
4763   "Generate a SUBJECT for a forwarded message.
4764 The form is: Fwd: Subject, where Subject is the original subject of
4765 the message."
4766   (concat "Fwd: " subject))
4767
4768 (defun message-make-forward-subject ()
4769   "Return a Subject header suitable for the message in the current buffer."
4770   (save-excursion
4771     (save-restriction
4772       (message-narrow-to-head-1)
4773       (let ((funcs message-make-forward-subject-function)
4774             (subject (message-fetch-field "Subject")))
4775         (setq subject
4776               (if subject
4777                   (if message-forward-decoded-p
4778                       subject
4779                     (mail-decode-encoded-word-string subject))
4780                 ""))
4781         (if message-wash-forwarded-subjects
4782             (setq subject (message-wash-subject subject)))
4783         ;; Make sure funcs is a list.
4784         (and funcs
4785              (not (listp funcs))
4786              (setq funcs (list funcs)))
4787         ;; Apply funcs in order, passing subject generated by previous
4788         ;; func to the next one.
4789         (while funcs
4790           (when (message-functionp (car funcs))
4791             (setq subject (funcall (car funcs) subject)))
4792           (setq funcs (cdr funcs)))
4793         subject))))
4794
4795 (eval-when-compile
4796   (defvar gnus-article-decoded-p))
4797
4798
4799 ;;;###autoload
4800 (defun message-forward (&optional news digest)
4801   "Forward the current message via mail.
4802 Optional NEWS will use news to forward instead of mail.
4803 Optional DIGEST will use digest to forward."
4804   (interactive "P")
4805   (let* ((cur (current-buffer))
4806          (message-forward-decoded-p
4807           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
4808               gnus-article-decoded-p ;; In an article buffer.
4809             message-forward-decoded-p))
4810          (subject (message-make-forward-subject)))
4811     (if news
4812         (message-news nil subject)
4813       (message-mail nil subject))
4814     (message-forward-make-body cur digest)))
4815
4816 ;;;###autoload
4817 (defun message-forward-make-body (forward-buffer &optional digest)
4818   ;; Put point where we want it before inserting the forwarded
4819   ;; message.
4820   (if message-forward-before-signature
4821       (message-goto-body)
4822     (goto-char (point-max)))
4823   (if message-forward-as-mime
4824       (if digest
4825           (insert "\n<#multipart type=digest>\n")
4826         (if message-forward-show-mml
4827             (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4828           (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4829     (insert "\n-------------------- Start of forwarded message --------------------\n"))
4830   (let ((b (point)) e)
4831     (if digest
4832         (if message-forward-as-mime
4833             (insert-buffer-substring forward-buffer)
4834           (mml-insert-buffer forward-buffer))
4835       (if (and message-forward-show-mml
4836                (not message-forward-decoded-p))
4837           (insert
4838            (with-temp-buffer
4839              (mm-disable-multibyte-mule4) ;; Must copy buffer in unibyte mode
4840                (insert
4841                 (with-current-buffer forward-buffer
4842                   (mm-string-as-unibyte (buffer-string))))
4843                (mm-enable-multibyte-mule4)
4844                (mime-to-mml)
4845                (goto-char (point-min))
4846                (when (looking-at "From ")
4847                  (replace-match "X-From-Line: "))
4848                (buffer-string)))
4849         (save-restriction
4850           (narrow-to-region (point) (point))
4851           (mml-insert-buffer forward-buffer)
4852           (goto-char (point-min))
4853           (when (looking-at "From ")
4854             (replace-match "X-From-Line: "))
4855           (goto-char (point-max)))))
4856     (setq e (point))
4857     (if message-forward-as-mime
4858         (if digest
4859             (insert "<#/multipart>\n")
4860           (if message-forward-show-mml
4861               (insert "<#/mml>\n")
4862             (insert "<#/part>\n")))
4863       (insert "\n-------------------- End of forwarded message --------------------\n"))
4864     (if (and digest message-forward-as-mime)
4865         (save-restriction
4866           (narrow-to-region b e)
4867           (goto-char b)
4868           (narrow-to-region (point)
4869                             (or (search-forward "\n\n" nil t) (point)))
4870           (delete-region (point-min) (point-max)))
4871       (when (and (not current-prefix-arg)
4872                  message-forward-ignored-headers)
4873         (save-restriction
4874           (narrow-to-region b e)
4875           (goto-char b)
4876           (narrow-to-region (point)
4877                             (or (search-forward "\n\n" nil t) (point)))
4878           (message-remove-header message-forward-ignored-headers t)))))
4879   (message-position-point))
4880
4881 ;;;###autoload
4882 (defun message-forward-rmail-make-body (forward-buffer)
4883   (save-window-excursion
4884     (set-buffer forward-buffer)
4885     (let (rmail-enable-mime)
4886       (rmail-toggle-header 0)))
4887   (message-forward-make-body forward-buffer))
4888
4889 ;;;###autoload
4890 (defun message-insinuate-rmail ()
4891   "Let RMAIL uses message to forward."
4892   (interactive)
4893   (setq rmail-enable-mime-composing t)
4894   (setq rmail-insert-mime-forwarded-message-function 
4895         'message-forward-rmail-make-body))
4896
4897 ;;;###autoload
4898 (defun message-resend (address)
4899   "Resend the current article to ADDRESS."
4900   (interactive
4901    (list (message-read-from-minibuffer "Resend message to: ")))
4902   (message "Resending message to %s..." address)
4903   (save-excursion
4904     (let ((cur (current-buffer))
4905           beg)
4906       ;; We first set up a normal mail buffer.
4907       (unless (message-mail-user-agent)
4908         (set-buffer (get-buffer-create " *message resend*"))
4909         (erase-buffer))
4910       (let ((message-this-is-mail t))
4911         (message-setup `((To . ,address))))
4912       ;; Insert our usual headers.
4913       (message-generate-headers '(From Date To))
4914       (message-narrow-to-headers)
4915       ;; Rename them all to "Resent-*".
4916       (while (re-search-forward "^[A-Za-z]" nil t)
4917         (forward-char -1)
4918         (insert "Resent-"))
4919       (widen)
4920       (forward-line)
4921       (delete-region (point) (point-max))
4922       (setq beg (point))
4923       ;; Insert the message to be resent.
4924       (insert-buffer-substring cur)
4925       (goto-char (point-min))
4926       (search-forward "\n\n")
4927       (forward-char -1)
4928       (save-restriction
4929         (narrow-to-region beg (point))
4930         (message-remove-header message-ignored-resent-headers t)
4931         (goto-char (point-max)))
4932       (insert mail-header-separator)
4933       ;; Rename all old ("Also-")Resent headers.
4934       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4935         (beginning-of-line)
4936         (insert "Also-"))
4937       ;; Quote any "From " lines at the beginning.
4938       (goto-char beg)
4939       (when (looking-at "From ")
4940         (replace-match "X-From-Line: "))
4941       ;; Send it.
4942       (let ((message-inhibit-body-encoding t)
4943             message-required-mail-headers)
4944         (message-send-mail))
4945       (kill-buffer (current-buffer)))
4946     (message "Resending message to %s...done" address)))
4947
4948 ;;;###autoload
4949 (defun message-bounce ()
4950   "Re-mail the current message.
4951 This only makes sense if the current message is a bounce message that
4952 contains some mail you have written which has been bounced back to
4953 you."
4954   (interactive)
4955   (let ((handles (mm-dissect-buffer t))
4956         boundary)
4957     (message-pop-to-buffer (message-buffer-name "bounce"))
4958     (if (stringp (car handles))
4959         ;; This is a MIME bounce.
4960         (mm-insert-part (car (last handles)))
4961       ;; This is a non-MIME bounce, so we try to remove things
4962       ;; manually.
4963       (mm-insert-part handles)
4964       (undo-boundary)
4965       (goto-char (point-min))
4966       (search-forward "\n\n" nil t)
4967       (if (or (and (re-search-forward message-unsent-separator nil t)
4968                    (forward-line 1))
4969               (re-search-forward "^Return-Path:.*\n" nil t))
4970           ;; We remove everything before the bounced mail.
4971           (delete-region
4972            (point-min)
4973            (if (re-search-forward "^[^ \n\t]+:" nil t)
4974                (match-beginning 0)
4975              (point)))
4976         (when (re-search-backward "^.?From .*\n" nil t)
4977           (delete-region (match-beginning 0) (match-end 0)))))
4978     (mm-enable-multibyte)
4979     (mime-to-mml)
4980     (save-restriction
4981       (message-narrow-to-head-1)
4982       (message-remove-header message-ignored-bounced-headers t)
4983       (goto-char (point-max))
4984       (insert mail-header-separator))
4985     (message-position-point)))
4986
4987 ;;;
4988 ;;; Interactive entry points for new message buffers.
4989 ;;;
4990
4991 ;;;###autoload
4992 (defun message-mail-other-window (&optional to subject)
4993   "Like `message-mail' command, but display mail buffer in another window."
4994   (interactive)
4995   (unless (message-mail-user-agent)
4996     (let ((pop-up-windows t)
4997           (special-display-buffer-names nil)
4998           (special-display-regexps nil)
4999           (same-window-buffer-names nil)
5000           (same-window-regexps nil))
5001       (message-pop-to-buffer (message-buffer-name "mail" to))))
5002   (let ((message-this-is-mail t))
5003     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5004                    nil nil 'switch-to-buffer-other-window)))
5005
5006 ;;;###autoload
5007 (defun message-mail-other-frame (&optional to subject)
5008   "Like `message-mail' command, but display mail buffer in another frame."
5009   (interactive)
5010   (unless (message-mail-user-agent)
5011     (let ((pop-up-frames t)
5012           (special-display-buffer-names nil)
5013           (special-display-regexps nil)
5014           (same-window-buffer-names nil)
5015           (same-window-regexps nil))
5016       (message-pop-to-buffer (message-buffer-name "mail" to))))
5017   (let ((message-this-is-mail t))
5018     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5019                    nil nil 'switch-to-buffer-other-frame)))
5020
5021 ;;;###autoload
5022 (defun message-news-other-window (&optional newsgroups subject)
5023   "Start editing a news article to be sent."
5024   (interactive)
5025   (let ((pop-up-windows t)
5026         (special-display-buffer-names nil)
5027         (special-display-regexps nil)
5028         (same-window-buffer-names nil)
5029         (same-window-regexps nil))
5030     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5031   (let ((message-this-is-news t))
5032     (message-setup `((Newsgroups . ,(or newsgroups ""))
5033                      (Subject . ,(or subject ""))))))
5034
5035 ;;;###autoload
5036 (defun message-news-other-frame (&optional newsgroups subject)
5037   "Start editing a news article to be sent."
5038   (interactive)
5039   (let ((pop-up-frames t)
5040         (special-display-buffer-names nil)
5041         (special-display-regexps nil)
5042         (same-window-buffer-names nil)
5043         (same-window-regexps nil))
5044     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5045   (let ((message-this-is-news t))
5046     (message-setup `((Newsgroups . ,(or newsgroups ""))
5047                      (Subject . ,(or subject ""))))))
5048
5049 ;;; underline.el
5050
5051 ;; This code should be moved to underline.el (from which it is stolen).
5052
5053 ;;;###autoload
5054 (defun bold-region (start end)
5055   "Bold all nonblank characters in the region.
5056 Works by overstriking characters.
5057 Called from program, takes two arguments START and END
5058 which specify the range to operate on."
5059   (interactive "r")
5060   (save-excursion
5061     (let ((end1 (make-marker)))
5062       (move-marker end1 (max start end))
5063       (goto-char (min start end))
5064       (while (< (point) end1)
5065         (or (looking-at "[_\^@- ]")
5066             (insert (char-after) "\b"))
5067         (forward-char 1)))))
5068
5069 ;;;###autoload
5070 (defun unbold-region (start end)
5071   "Remove all boldness (overstruck characters) in the region.
5072 Called from program, takes two arguments START and END
5073 which specify the range to operate on."
5074   (interactive "r")
5075   (save-excursion
5076     (let ((end1 (make-marker)))
5077       (move-marker end1 (max start end))
5078       (goto-char (min start end))
5079       (while (re-search-forward "\b" end1 t)
5080         (if (eq (char-after) (char-after (- (point) 2)))
5081             (delete-char -2))))))
5082
5083 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5084
5085 ;; Support for toolbar
5086 (eval-when-compile
5087   (defvar tool-bar-map)
5088   (defvar tool-bar-mode))
5089
5090 (defun message-tool-bar-map ()
5091   (or message-tool-bar-map
5092       (setq message-tool-bar-map
5093             (and (fboundp 'tool-bar-add-item-from-menu)
5094                  tool-bar-mode
5095                  (let ((tool-bar-map (copy-keymap tool-bar-map))
5096                        (load-path (mm-image-load-path)))
5097                    ;; Zap some items which aren't so relevant and take
5098                    ;; up space.
5099                    (dolist (key '(print-buffer kill-buffer save-buffer
5100                                                write-file dired open-file))
5101                      (define-key tool-bar-map (vector key) nil))
5102                    (tool-bar-add-item-from-menu
5103                     'message-send-and-exit "mail_send" message-mode-map)
5104                    (tool-bar-add-item-from-menu
5105                     'message-kill-buffer "close" message-mode-map)
5106                    (tool-bar-add-item-from-menu
5107                     'message-dont-send "cancel" message-mode-map)
5108                    (tool-bar-add-item-from-menu
5109                     'mml-attach-file "attach" mml-mode-map)
5110                    (tool-bar-add-item-from-menu
5111                     'ispell-message "spell" message-mode-map)
5112                    (tool-bar-add-item-from-menu
5113                     'message-insert-importance-high "important"
5114                     message-mode-map)
5115                    (tool-bar-add-item-from-menu
5116                     'message-insert-importance-low "unimportant"
5117                     message-mode-map)
5118                    tool-bar-map)))))
5119
5120 ;;; Group name completion.
5121
5122 (defvar message-newgroups-header-regexp
5123   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5124   "Regexp that match headers that lists groups.")
5125
5126 (defvar message-completion-alist
5127   (list (cons message-newgroups-header-regexp 'message-expand-group)
5128         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name))
5129   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE.")
5130
5131 (defvar message-tab-body-function 'indent-relative
5132   "*Function to execute when `message-tab' (TAB) is executed in the body.")
5133
5134 (defun message-tab ()
5135   "Complete names according to `message-completion-alist'.
5136 Do an `indent-relative' if not in those headers."
5137   (interactive)
5138   (let ((alist message-completion-alist))
5139     (while (and alist
5140                 (let ((mail-abbrev-mode-regexp (caar alist)))
5141                   (not (mail-abbrev-in-expansion-header-p))))
5142       (setq alist (cdr alist)))
5143     (funcall (or (cdar alist) message-tab-body-function))))
5144
5145 (defun message-expand-group ()
5146   "Expand the group name under point."
5147   (let* ((b (save-excursion
5148               (save-restriction
5149                 (narrow-to-region
5150                  (save-excursion
5151                    (beginning-of-line)
5152                    (skip-chars-forward "^:")
5153                    (1+ (point)))
5154                  (point))
5155                 (skip-chars-backward "^, \t\n") (point))))
5156          (completion-ignore-case t)
5157          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5158                                             (point))))
5159          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5160          (completions (all-completions string hashtb))
5161          comp)
5162     (delete-region b (point))
5163     (cond
5164      ((= (length completions) 1)
5165       (if (string= (car completions) string)
5166           (progn
5167             (insert string)
5168             (message "Only matching group"))
5169         (insert (car completions))))
5170      ((and (setq comp (try-completion string hashtb))
5171            (not (string= comp string)))
5172       (insert comp))
5173      (t
5174       (insert string)
5175       (if (not comp)
5176           (message "No matching groups")
5177         (save-selected-window
5178           (pop-to-buffer "*Completions*")
5179           (buffer-disable-undo)
5180           (let ((buffer-read-only nil))
5181             (erase-buffer)
5182             (let ((standard-output (current-buffer)))
5183               (display-completion-list (sort completions 'string<)))
5184             (goto-char (point-min))
5185             (delete-region (point) (progn (forward-line 3) (point))))))))))
5186
5187 (defun message-expand-name ()
5188   (if (fboundp 'bbdb-complete-name)
5189       (bbdb-complete-name)
5190     (expand-abbrev)))
5191
5192 ;;; Help stuff.
5193
5194 (defun message-talkative-question (ask question show &rest text)
5195   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
5196 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
5197 The following arguments may contain lists of values."
5198   (if (and show
5199            (setq text (message-flatten-list text)))
5200       (save-window-excursion
5201         (save-excursion
5202           (with-output-to-temp-buffer " *MESSAGE information message*"
5203             (set-buffer " *MESSAGE information message*")
5204             (fundamental-mode)          ; for Emacs 20.4+
5205             (mapcar 'princ text)
5206             (goto-char (point-min))))
5207         (funcall ask question))
5208     (funcall ask question)))
5209
5210 (defun message-flatten-list (list)
5211   "Return a new, flat list that contains all elements of LIST.
5212
5213 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
5214 => (1 2 3 4 5 6 7)"
5215   (cond ((consp list)
5216          (apply 'append (mapcar 'message-flatten-list list)))
5217         (list
5218          (list list))))
5219
5220 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
5221   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
5222 Then clone the local variables and values from the old buffer to the
5223 new one, cloning only the locals having a substring matching the
5224 regexp varstr."
5225   (let ((oldbuf (current-buffer)))
5226     (save-excursion
5227       (set-buffer (generate-new-buffer name))
5228       (message-clone-locals oldbuf varstr)
5229       (current-buffer))))
5230
5231 (defun message-clone-locals (buffer &optional varstr)
5232   "Clone the local variables from BUFFER to the current buffer."
5233   (let ((locals (save-excursion
5234                   (set-buffer buffer)
5235                   (buffer-local-variables)))
5236         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
5237     (mapcar
5238      (lambda (local)
5239        (when (and (consp local)
5240                   (car local)
5241                   (string-match regexp (symbol-name (car local)))
5242                   (or (null varstr)
5243                       (string-match varstr (symbol-name (car local)))))
5244          (ignore-errors
5245            (set (make-local-variable (car local))
5246                 (cdr local)))))
5247      locals)))
5248
5249 ;;; Miscellaneous functions
5250
5251 (defsubst message-replace-chars-in-string (string from to)
5252   (mm-subst-char-in-string from to string))
5253
5254 ;;;
5255 ;;; MIME functions
5256 ;;;
5257
5258 (defvar message-inhibit-body-encoding nil)
5259
5260 (defun message-encode-message-body ()
5261   (unless message-inhibit-body-encoding
5262     (let ((mail-parse-charset (or mail-parse-charset
5263                                   message-default-charset))
5264           (case-fold-search t)
5265           lines content-type-p)
5266       (message-goto-body)
5267       (save-restriction
5268         (narrow-to-region (point) (point-max))
5269         (let ((new (mml-generate-mime)))
5270           (when new
5271             (delete-region (point-min) (point-max))
5272             (insert new)
5273             (goto-char (point-min))
5274             (if (eq (aref new 0) ?\n)
5275                 (delete-char 1)
5276               (search-forward "\n\n")
5277               (setq lines (buffer-substring (point-min) (1- (point))))
5278               (delete-region (point-min) (point))))))
5279       (save-restriction
5280         (message-narrow-to-headers-or-head)
5281         (message-remove-header "Mime-Version")
5282         (goto-char (point-max))
5283         (insert "MIME-Version: 1.0\n")
5284         (when lines
5285           (insert lines))
5286         (setq content-type-p
5287               (or mml-boundary
5288                   (re-search-backward "^Content-Type:" nil t))))
5289       (save-restriction
5290         (message-narrow-to-headers-or-head)
5291         (message-remove-first-header "Content-Type")
5292         (message-remove-first-header "Content-Transfer-Encoding"))
5293       ;; We always make sure that the message has a Content-Type header.
5294       ;; This is because some broken MTAs and MUAs get awfully confused
5295       ;; when confronted with a message with a MIME-Version header and
5296       ;; without a Content-Type header.  For instance, Solaris'
5297       ;; /usr/bin/mail.
5298       (unless content-type-p
5299         (goto-char (point-min))
5300         ;; For unknown reason, MIME-Version doesn't exist.
5301         (when (re-search-forward "^MIME-Version:" nil t)
5302           (forward-line 1)
5303           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
5304
5305 (defun message-read-from-minibuffer (prompt)
5306   "Read from the minibuffer while providing abbrev expansion."
5307   (if (fboundp 'mail-abbrevs-setup)
5308       (let ((mail-abbrev-mode-regexp "")
5309             (minibuffer-setup-hook 'mail-abbrevs-setup)
5310             (minibuffer-local-map message-minibuffer-local-map))
5311         (read-from-minibuffer prompt))
5312     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
5313           (minibuffer-local-map message-minibuffer-local-map))
5314       (read-string prompt))))
5315
5316 (defun message-use-alternative-email-as-from ()
5317   (require 'mail-utils)
5318   (let* ((fields '("To" "Cc"))
5319          (emails
5320           (split-string
5321            (mail-strip-quoted-names
5322             (mapconcat 'message-fetch-reply-field fields ","))
5323            "[ \f\t\n\r\v,]+"))
5324          email)
5325     (while emails
5326       (if (string-match message-alternative-emails (car emails))
5327           (setq email (car emails)
5328                 emails nil))
5329       (pop emails))
5330     (unless (or (not email) (equal email user-mail-address))
5331       (goto-char (point-max))
5332       (insert "From: " email "\n"))))
5333
5334 (defun message-options-get (symbol)
5335   (cdr (assq symbol message-options)))
5336
5337 (defun message-options-set (symbol value)
5338   (let ((the-cons (assq symbol message-options)))
5339     (if the-cons
5340         (if value
5341             (setcdr the-cons value)
5342           (setq message-options (delq the-cons message-options)))
5343       (and value
5344            (push (cons symbol value) message-options))))
5345   value)
5346
5347 (defun message-options-set-recipient ()
5348   (save-restriction
5349     (message-narrow-to-headers-or-head)
5350     (message-options-set 'message-sender
5351                          (mail-strip-quoted-names
5352                           (message-fetch-field "from")))
5353     (message-options-set 'message-recipients
5354                          (mail-strip-quoted-names
5355                           (let ((to (message-fetch-field "to"))
5356                                 (cc (message-fetch-field "cc"))
5357                                 (bcc (message-fetch-field "bcc")))
5358                             (concat
5359                              (or to "")
5360                              (if (and to cc) ", ")
5361                              (or cc "")
5362                              (if (and (or to cc) bcc) ", ")
5363                              (or bcc "")))))))
5364
5365 (when (featurep 'xemacs)
5366   (require 'messagexmas)
5367   (message-xmas-redefine))
5368
5369 (provide 'message)
5370
5371 (run-hooks 'message-load-hook)
5372
5373 ;; Local Variables:
5374 ;; coding: iso-8859-1
5375 ;; End:
5376
5377 ;;; message.el ends here