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