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