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