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