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