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