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