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