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