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