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