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