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