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