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