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