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