Sync up with Pterodactyl Gnus 0.10.
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;;      Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
7 ;;      Keiichi Suzuki <kei-suzu@mail.wbs.ne.jp>
8 ;; Keywords: mail, news, MIME
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; This mode provides mail-sending facilities from within Emacs.  It
30 ;; consists mainly of large chunks of code from the sendmail.el,
31 ;; gnus-msg.el and rnewspost.el files.
32
33 ;;; Code:
34
35 (eval-when-compile
36   (require 'cl)
37   (require 'smtp)
38   )
39
40 (require 'mailheader)
41 (require 'nnheader)
42 (require 'timezone)
43 (require 'easymenu)
44 (require 'custom)
45 (if (string-match "XEmacs\\|Lucid" emacs-version)
46     (require 'mail-abbrevs)
47   (require 'mailabbrev))
48 (require 'mime-edit)
49
50 (defgroup message '((user-mail-address custom-variable)
51                     (user-full-name custom-variable))
52   "Mail and news message composing."
53   :link '(custom-manual "(message)Top")
54   :group 'mail
55   :group 'news)
56
57 (put 'user-mail-address 'custom-type 'string)
58 (put 'user-full-name 'custom-type 'string)
59
60 (defgroup message-various nil
61   "Various Message Variables"
62   :link '(custom-manual "(message)Various Message Variables")
63   :group 'message)
64
65 (defgroup message-buffers nil
66   "Message Buffers"
67   :link '(custom-manual "(message)Message Buffers")
68   :group 'message)
69
70 (defgroup message-sending nil
71   "Message Sending"
72   :link '(custom-manual "(message)Sending Variables")
73   :group 'message)
74
75 (defgroup message-interface nil
76   "Message Interface"
77   :link '(custom-manual "(message)Interface")
78   :group 'message)
79
80 (defgroup message-forwarding nil
81   "Message Forwarding"
82   :link '(custom-manual "(message)Forwarding")
83   :group 'message-interface)
84
85 (defgroup message-insertion nil
86   "Message Insertion"
87   :link '(custom-manual "(message)Insertion")
88   :group 'message)
89
90 (defgroup message-headers nil
91   "Message Headers"
92   :link '(custom-manual "(message)Message Headers")
93   :group 'message)
94
95 (defgroup message-news nil
96   "Composing News Messages"
97   :group 'message)
98
99 (defgroup message-mail nil
100   "Composing Mail Messages"
101   :group 'message)
102
103 (defgroup message-faces nil
104   "Faces used for message composing."
105   :group 'message
106   :group 'faces)
107
108 (defgroup message-frames nil
109   "Message frames"
110   :group 'message)
111
112 (defcustom message-directory "~/Mail/"
113   "*Directory from which all other mail file variables are derived."
114   :group 'message-various
115   :type 'directory)
116
117 (defcustom message-max-buffers 10
118   "*How many buffers to keep before starting to kill them off."
119   :group 'message-buffers
120   :type 'integer)
121
122 (defcustom message-send-rename-function nil
123   "Function called to rename the buffer after sending it."
124   :group 'message-buffers
125   :type 'function)
126
127 (defcustom message-fcc-handler-function 'message-output
128   "*A function called to save outgoing articles.
129 This function will be called with the name of the file to store the
130 article in.  The default function is `message-output' which saves in Unix
131 mailbox format."
132   :type '(radio (function-item message-output)
133                 (function :tag "Other"))
134   :group 'message-sending)
135
136 (defcustom message-encode-function 'message-maybe-encode
137   "*A function called to encode messages."
138   :group 'message-sending
139   :type 'function)
140
141 (defcustom message-courtesy-message
142   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
143   "*This is inserted at the start of a mailed copy of a posted message.
144 If the string contains the format spec \"%s\", the Newsgroups
145 the article has been posted to will be inserted there.
146 If this variable is nil, no such courtesy message will be added."
147   :group 'message-sending
148   :type 'string)
149
150 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
151   "*Regexp that matches headers to be removed in resent bounced mail."
152   :group 'message-interface
153   :type 'regexp)
154
155 ;;;###autoload
156 (defcustom message-from-style 'default
157   "*Specifies how \"From\" headers look.
158
159 If `nil', they contain just the return address like:
160         king@grassland.com
161 If `parens', they look like:
162         king@grassland.com (Elvis Parsley)
163 If `angles', they look like:
164         Elvis Parsley <king@grassland.com>
165
166 Otherwise, most addresses look like `angles', but they look like
167 `parens' if `angles' would need quoting and `parens' would not."
168   :type '(choice (const :tag "simple" nil)
169                  (const parens)
170                  (const angles)
171                  (const default))
172   :group 'message-headers)
173
174 (defcustom message-syntax-checks nil
175   ; Guess this one shouldn't be easy to customize...
176   "*Controls what syntax checks should not be performed on outgoing posts.
177 To disable checking of long signatures, for instance, add
178  `(signature . disabled)' to this list.
179
180 Don't touch this variable unless you really know what you're doing.
181
182 Checks include subject-cmsg multiple-headers sendsys message-id from
183 long-lines control-chars size new-text redirected-followup signature
184 approved sender empty empty-headers message-id from subject
185 shorten-followup-to existing-newsgroups buffer-file-name unchanged."
186   :group 'message-news)
187
188 (defcustom message-required-news-headers
189   '(From Newsgroups Subject Date Message-ID
190          (optional . Organization) Lines
191          (optional . User-Agent))
192   "*Headers to be generated or prompted for when posting an article.
193 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
194 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
195 User-Agent are optional.  If don't you want message to insert some
196 header, remove it from this list."
197   :group 'message-news
198   :group 'message-headers
199   :type '(repeat sexp))
200
201 (defcustom message-required-mail-headers
202   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
203          (optional . User-Agent))
204   "*Headers to be generated or prompted for when mailing a message.
205 RFC822 required that From, Date, To, Subject and Message-ID be
206 included.  Organization, Lines and User-Agent are optional."
207   :group 'message-mail
208   :group 'message-headers
209   :type '(repeat sexp))
210
211 (defcustom message-deletable-headers '(Message-ID Date Lines)
212   "Headers to be deleted if they already exist and were generated by message previously."
213   :group 'message-headers
214   :type 'sexp)
215
216 (defcustom message-ignored-news-headers
217   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:"
218   "*Regexp of headers to be removed unconditionally before posting."
219   :group 'message-news
220   :group 'message-headers
221   :type 'regexp)
222
223 (defcustom message-ignored-mail-headers "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:"
224   "*Regexp of headers to be removed unconditionally before mailing."
225   :group 'message-mail
226   :group 'message-headers
227   :type 'regexp)
228
229 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:"
230   "*Header lines matching this regexp will be deleted before posting.
231 It's best to delete old Path and Date headers before posting to avoid
232 any confusion."
233   :group 'message-interface
234   :type 'regexp)
235
236 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
237   "*Regexp matching \"Re: \" in the subject line."
238   :group 'message-various
239   :type 'regexp)
240
241 ;;; Some sender agents encode the whole subject including leading "Re: ".
242 ;;; And if followup agent does not decode it for some reason (e.g. unknown
243 ;;; charset) and just add a new "Re: " in front of the encoded-word, the
244 ;;; result will contain multiple "Re: "'s.
245 (defcustom message-subject-encoded-re-regexp
246   (concat
247    "^[ \t]*"
248    (regexp-quote "=?")
249    "[-!#$%&'*+0-9A-Z^_`a-z{|}~]+" ; charset
250    (regexp-quote "?")
251    "\\("
252    "[Bb]" (regexp-quote "?") ; B encoding
253    "\\(\\(CQk\\|CSA\\|IAk\\|ICA\\)[Jg]\\)*" ; \([ \t][ \t][ \t]\)*
254    "\\("
255    "[Uc][km]U6" ; [Rr][Ee]:
256    "\\|"
257    "\\(C[VX]\\|I[FH]\\)J[Fl]O[g-v]" ; [ \t][Rr][Ee]:
258    "\\|"
259    "\\(CQl\\|CSB\\|IAl\\|ICB\\)[Sy][RZ]T[o-r]" ; [ \t][ \t][Rr][Ee]:
260    "\\)"
261    "\\|"
262    "[Qb]" (regexp-quote "?") ; Q encoding
263    "\\(_\\|=09\\|=20\\)*"
264    "\\([Rr]\\|=[57]2\\)\\([Ee]\\|=[46]5\\)\\(:\\|=3[Aa]\\)"
265    "\\)"
266    )
267   "*Regexp matching \"Re: \" in the subject line.
268 Unlike `message-subject-re-regexp', this regexp matches \"Re: \" within
269 an encoded-word."
270   :group 'message-various
271   :type 'regexp)
272
273 (defcustom message-use-subject-re t
274   "*If t, remove any (buggy) \"Re: \"'s from the subject of the precursor
275 and add a new \"Re: \".  If it is nil, use the subject \"as-is\".  If it
276 is the symbol `guess', try to detect \"Re: \" within an encoded-word."
277   :group 'message-various
278   :type '(choice (const :tag "off" nil)
279                  (const :tag "on" t)
280                  (const guess)))
281
282 ;;;###autoload
283 (defcustom message-signature-separator "^-- *$"
284   "Regexp matching the signature separator."
285   :type 'regexp
286   :group 'message-various)
287
288 (defcustom message-elide-elipsis "\n[...]\n\n"
289   "*The string which is inserted for elided text."
290   :type 'string
291   :group 'message-various)
292
293 (defcustom message-interactive nil
294   "Non-nil means when sending a message wait for and display errors.
295 nil means let mailer mail back a message to report errors."
296   :group 'message-sending
297   :group 'message-mail
298   :type 'boolean)
299
300 (defcustom message-generate-new-buffers t
301   "*Non-nil means that a new message buffer will be created whenever `message-setup' is called.
302 If this is a function, call that function with three parameters:  The type,
303 the to address and the group name.  (Any of these may be nil.)  The function
304 should return the new buffer name."
305   :group 'message-buffers
306   :type '(choice (const :tag "off" nil)
307                  (const :tag "on" t)
308                  (function fun)))
309
310 (defcustom message-kill-buffer-on-exit nil
311   "*Non-nil means that the message buffer will be killed after sending a message."
312   :group 'message-buffers
313   :type 'boolean)
314
315 (defvar gnus-local-organization)
316 (defcustom message-user-organization
317   (or (and (boundp 'gnus-local-organization)
318            (stringp gnus-local-organization)
319            gnus-local-organization)
320       (getenv "ORGANIZATION")
321       t)
322   "*String to be used as an Organization header.
323 If t, use `message-user-organization-file'."
324   :group 'message-headers
325   :type '(choice string
326                  (const :tag "consult file" t)))
327
328 ;;;###autoload
329 (defcustom message-user-organization-file "/usr/lib/news/organization"
330   "*Local news organization file."
331   :type 'file
332   :group 'message-headers)
333
334 (defcustom message-forward-start-separator
335   (concat (mime-make-tag "message" "rfc822") "\n")
336   "*Delimiter inserted before forwarded messages."
337   :group 'message-forwarding
338   :type 'string)
339
340 (defcustom message-forward-end-separator
341   (concat (mime-make-tag "text" "plain") "\n")
342   "*Delimiter inserted after forwarded messages."
343   :group 'message-forwarding
344   :type 'string)
345
346 (defcustom message-signature-before-forwarded-message t
347   "*If non-nil, put the signature before any included forwarded message."
348   :group 'message-forwarding
349   :type 'boolean)
350
351 (defcustom message-included-forward-headers
352   "^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:"
353   "*Regexp matching headers to be included in forwarded messages."
354   :group 'message-forwarding
355   :type 'regexp)
356
357 (defcustom message-make-forward-subject-function 
358   'message-forward-subject-author-subject
359  "*A list of functions that are called to generate a subject header for forwarded messages.
360 The subject generated by the previous function is passed into each
361 successive function.
362
363 The provided functions are:
364
365 * message-forward-subject-author-subject (Source of article (author or
366       newsgroup)), in brackets followed by the subject
367 * message-forward-subject-fwd (Subject of article with 'Fwd:' prepended
368       to it."
369  :group 'message-forwarding
370  :type '(radio (function-item message-forward-subject-author-subject)
371                (function-item message-forward-subject-fwd)))
372
373 (defcustom message-wash-forwarded-subjects nil
374   "*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."
375   :group 'message-forwarding
376   :type 'boolean)
377
378 (defcustom message-ignored-resent-headers "^Return-Receipt"
379   "*All headers that match this regexp will be deleted when resending a message."
380   :group 'message-interface
381   :type 'regexp)
382
383 (defcustom message-ignored-cited-headers "."
384   "*Delete these headers from the messages you yank."
385   :group 'message-insertion
386   :type 'regexp)
387
388 (defcustom message-cancel-message "I am canceling my own article."
389   "Message to be inserted in the cancel message."
390   :group 'message-interface
391   :type 'string)
392
393 ;; Useful to set in site-init.el
394 ;;;###autoload
395 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
396   "Function to call to send the current buffer as mail.
397 The headers should be delimited by a line whose contents match the
398 variable `mail-header-separator'.
399
400 Legal values include `message-send-mail-with-sendmail' (the default),
401 `message-send-mail-with-mh', `message-send-mail-with-qmail' and
402 `message-send-mail-with-smtp'."
403   :type '(radio (function-item message-send-mail-with-sendmail)
404                 (function-item message-send-mail-with-mh)
405                 (function-item message-send-mail-with-qmail)
406                 (function-item message-send-mail-with-smtp)
407                 (function :tag "Other"))
408   :group 'message-sending
409   :group 'message-mail)
410
411 ;; 1997-09-29 by MORIOKA Tomohiko
412 (defcustom message-send-news-function 'message-send-news-with-gnus
413   "Function to call to send the current buffer as news.
414 The headers should be delimited by a line whose contents match the
415 variable `mail-header-separator'."
416   :group 'message-sending
417   :group 'message-news
418   :type 'function)
419
420 (defcustom message-reply-to-function nil
421   "Function that should return a list of headers.
422 This function should pick out addresses from the To, Cc, and From headers
423 and respond with new To and Cc headers."
424   :group 'message-interface
425   :type 'function)
426
427 (defcustom message-wide-reply-to-function nil
428   "Function that should return a list of headers.
429 This function should pick out addresses from the To, Cc, and From headers
430 and respond with new To and Cc headers."
431   :group 'message-interface
432   :type 'function)
433
434 (defcustom message-followup-to-function nil
435   "Function that should return a list of headers.
436 This function should pick out addresses from the To, Cc, and From headers
437 and respond with new To and Cc headers."
438   :group 'message-interface
439   :type 'function)
440
441 (defcustom message-use-followup-to 'ask
442   "*Specifies what to do with Followup-To header.
443 If nil, always ignore the header.  If it is t, use its value, but
444 query before using the \"poster\" value.  If it is the symbol `ask',
445 always query the user whether to use the value.  If it is the symbol
446 `use', always use the value."
447   :group 'message-interface
448   :type '(choice (const :tag "ignore" nil)
449                  (const :tag "maybe" t)
450                  (const :tag "always" use)
451                  (const :tag "ask" ask)))
452
453 (defcustom message-use-mail-copies-to 'ask
454   "*Specifies what to do with Mail-Copies-To header.
455 If nil, always ignore the header.  If it is t, use its value, but
456 query before using the value other than \"always\" or \"never\".
457 If it is the symbol `ask', always query the user whether to use
458 the value.  If it is the symbol `use', always use the value."
459   :group 'message-interface
460   :type '(choice (const :tag "ignore" nil)
461                  (const :tag "maybe" t)
462                  (const :tag "always" use)
463                  (const :tag "ask" ask)))
464
465 (defcustom message-use-mail-followup-to 'ask
466   "*Specifies what to do with Mail-Followup-To header.
467 If nil, always ignore the header.  If it is the symbol `ask', always
468 query the user whether to use the value.  If it is t or the symbol
469 `use', always use the value."
470   :group 'message-interface
471   :type '(choice (const :tag "ignore" nil)
472                  (const :tag "maybe" t)
473                  (const :tag "always" use)
474                  (const :tag "ask" ask)))
475
476 ;;; XXX: 'ask and 'use are not implemented yet.
477 (defcustom message-use-mail-reply-to 'ask
478   "*Specifies what to do with Mail-Reply-To/Reply-To header.
479 If nil, always ignore the header.  If it is t or the symbol `use', use
480 its value.  If it is the symbol `ask', always query the user whether to
481 use the value.  Note that if \"Reply-To\" is marked as \"broken\", its value
482 is never used."
483   :group 'message-interface
484   :type '(choice (const :tag "ignore" nil)
485                  (const :tag "maybe" t)
486                  (const :tag "always" use)
487                  (const :tag "ask" ask)))
488
489 ;; stuff relating to broken sendmail in MMDF
490 (defcustom message-sendmail-f-is-evil nil
491   "*Non-nil means that \"-f username\" should not be added to the sendmail
492 command line, because it is even more evil than leaving it out."
493   :group 'message-sending
494   :type 'boolean)
495
496 ;; qmail-related stuff
497 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
498   "Location of the qmail-inject program."
499   :group 'message-sending
500   :type 'file)
501
502 (defcustom message-qmail-inject-args nil
503   "Arguments passed to qmail-inject programs.
504 This should be a list of strings, one string for each argument.
505
506 For e.g., if you wish to set the envelope sender address so that bounces
507 go to the right place or to deal with listserv's usage of that address, you
508 might set this variable to '(\"-f\" \"you@some.where\")."
509   :group 'message-sending
510   :type '(repeat string))
511
512 (defvar gnus-post-method)
513 (defvar gnus-select-method)
514 (defcustom message-post-method
515   (cond ((and (boundp 'gnus-post-method)
516               (listp gnus-post-method)
517               gnus-post-method)
518          gnus-post-method)
519         ((boundp 'gnus-select-method)
520          gnus-select-method)
521         (t '(nnspool "")))
522   "*Method used to post news.
523 Note that when posting from inside Gnus, for instance, this
524 variable isn't used."
525   :group 'message-news
526   :group 'message-sending
527   ;; This should be the `gnus-select-method' widget, but that might
528   ;; create a dependence to `gnus.el'.
529   :type 'sexp)
530
531 (defcustom message-generate-headers-first nil
532   "*If non-nil, generate all possible headers before composing."
533   :group 'message-headers
534   :type 'boolean)
535
536 (defcustom message-setup-hook
537   '(message-maybe-setup-default-charset turn-on-mime-edit)
538   "Normal hook, run each time a new outgoing message is initialized.
539 The function `message-setup' runs this hook."
540   :group 'message-various
541   :type 'hook)
542
543 (defcustom message-signature-setup-hook nil
544   "Normal hook, run each time a new outgoing message is initialized.
545 It is run after the headers have been inserted and before
546 the signature is inserted."
547   :group 'message-various
548   :type 'hook)
549
550 (defcustom message-mode-hook nil
551   "Hook run in message mode buffers."
552   :group 'message-various
553   :type 'hook)
554
555 (defcustom message-header-hook '(eword-encode-header)
556   "Hook run in a message mode buffer narrowed to the headers."
557   :group 'message-various
558   :type 'hook)
559
560 (defcustom message-header-setup-hook nil
561   "Hook called narrowed to the headers when setting up a message buffer."
562   :group 'message-various
563   :type 'hook)
564
565 ;;;###autoload
566 (defcustom message-citation-line-function 'message-insert-citation-line
567   "*Function called to insert the \"Whomever writes:\" line."
568   :type 'function
569   :group 'message-insertion)
570
571 ;;;###autoload
572 (defcustom message-yank-prefix "> "
573   "*Prefix inserted on the lines of yanked messages.
574 nil means use indentation."
575   :type 'string
576   :group 'message-insertion)
577
578 (defcustom message-indentation-spaces 3
579   "*Number of spaces to insert at the beginning of each cited line.
580 Used by `message-yank-original' via `message-yank-cite'."
581   :group 'message-insertion
582   :type 'integer)
583
584 ;;;###autoload
585 (defcustom message-cite-function 'message-cite-original
586   "*Function for citing an original message.
587 Predefined functions include `message-cite-original' and
588 `message-cite-original-without-signature'.
589 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
590   :type '(radio (function-item message-cite-original)
591                 (function-item sc-cite-original)
592                 (function :tag "Other"))
593   :group 'message-insertion)
594
595 ;;;###autoload
596 (defcustom message-indent-citation-function 'message-indent-citation
597   "*Function for modifying a citation just inserted in the mail buffer.
598 This can also be a list of functions.  Each function can find the
599 citation between (point) and (mark t).  And each function should leave
600 point and mark around the citation text as modified."
601   :type 'function
602   :group 'message-insertion)
603
604 (defvar message-abbrevs-loaded nil)
605
606 ;;;###autoload
607 (defcustom message-signature t
608   "*String to be inserted at the end of the message buffer.
609 If t, the `message-signature-file' file will be inserted instead.
610 If a function, the result from the function will be used instead.
611 If a form, the result from the form will be used instead."
612   :type 'sexp
613   :group 'message-insertion)
614
615 ;;;###autoload
616 (defcustom message-signature-file "~/.signature"
617   "*File containing the text inserted at end of message buffer."
618   :type 'file
619   :group 'message-insertion)
620
621 (defcustom message-distribution-function nil
622   "*Function called to return a Distribution header."
623   :group 'message-news
624   :group 'message-headers
625   :type 'function)
626
627 (defcustom message-expires 14
628   "Number of days before your article expires."
629   :group 'message-news
630   :group 'message-headers
631   :link '(custom-manual "(message)News Headers")
632   :type 'integer)
633
634 (defcustom message-user-path nil
635   "If nil, use the NNTP server name in the Path header.
636 If stringp, use this; if non-nil, use no host name (user name only)."
637   :group 'message-news
638   :group 'message-headers
639   :link '(custom-manual "(message)News Headers")
640   :type '(choice (const :tag "nntp" nil)
641                  (string :tag "name")
642                  (sexp :tag "none" :format "%t" t)))
643
644 (defvar message-reply-buffer nil)
645 (defvar message-reply-headers nil)
646 (defvar message-sent-message-via nil)
647 (defvar message-checksum nil)
648 (defvar message-send-actions nil
649   "A list of actions to be performed upon successful sending of a message.")
650 (defvar message-exit-actions nil
651   "A list of actions to be performed upon exiting after sending a message.")
652 (defvar message-kill-actions nil
653   "A list of actions to be performed before killing a message buffer.")
654 (defvar message-postpone-actions nil
655   "A list of actions to be performed after postponing a message.")
656 (defvar message-original-frame nil)
657
658 (define-widget 'message-header-lines 'text
659   "All header lines must be LFD terminated."
660   :format "%t:%n%v"
661   :valid-regexp "^\\'"
662   :error "All header lines must be newline terminated")
663
664 (defcustom message-default-headers ""
665   "*A string containing header lines to be inserted in outgoing messages.
666 It is inserted before you edit the message, so you can edit or delete
667 these lines."
668   :group 'message-headers
669   :type 'message-header-lines)
670
671 (defcustom message-default-mail-headers ""
672   "*A string of header lines to be inserted in outgoing mails."
673   :group 'message-headers
674   :group 'message-mail
675   :type 'message-header-lines)
676
677 (defcustom message-default-news-headers ""
678   "*A string of header lines to be inserted in outgoing news
679 articles."
680   :group 'message-headers
681   :group 'message-news
682   :type 'message-header-lines)
683
684 ;; Note: could use /usr/ucb/mail instead of sendmail;
685 ;; options -t, and -v if not interactive.
686 (defcustom message-mailer-swallows-blank-line
687   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
688                          system-configuration)
689            (file-readable-p "/etc/sendmail.cf")
690            (let ((buffer (get-buffer-create " *temp*")))
691              (unwind-protect
692                  (save-excursion
693                    (set-buffer buffer)
694                    (insert-file-contents "/etc/sendmail.cf")
695                    (goto-char (point-min))
696                    (let ((case-fold-search nil))
697                      (re-search-forward "^OR\\>" nil t)))
698                (kill-buffer buffer))))
699       ;; According to RFC822, "The field-name must be composed of printable
700       ;; ASCII characters (i. e., characters that have decimal values between
701       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
702       ;; space, or colon.
703       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
704   "*Set this non-nil if the system's mailer runs the header and body together.
705 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
706 The value should be an expression to test whether the problem will
707 actually occur."
708   :group 'message-sending
709   :type 'sexp)
710
711 ;;; XXX: This symbol is overloaded!  See below.
712 (defvar message-user-agent nil
713   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
714
715 ;; Ignore errors in case this is used in Emacs 19.
716 ;; Don't use ignore-errors because this is copied into loaddefs.el.
717 ;;;###autoload
718 (condition-case nil
719     (define-mail-user-agent 'message-user-agent
720       'message-mail 'message-send-and-exit
721       'message-kill-buffer 'message-send-hook)
722   (error nil))
723
724 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
725   "If non-nil, delete the deletable headers before feeding to mh.")
726
727 (defvar message-send-method-alist
728   '((news message-news-p message-send-via-news)
729     (mail message-mail-p message-send-via-mail))
730   "Alist of ways to send outgoing messages.
731 Each element has the form
732
733   \(TYPE PREDICATE FUNCTION)
734
735 where TYPE is a symbol that names the method; PREDICATE is a function
736 called without any parameters to determine whether the message is
737 a message of type TYPE; and FUNCTION is a function to be called if
738 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
739 the prefix.")
740
741 (defvar message-mail-alias-type 'abbrev
742   "*What alias expansion type to use in Message buffers.
743 The default is `abbrev', which uses mailabbrev.  nil switches
744 mail aliases off.")
745
746 (defcustom message-autosave-directory
747   (nnheader-concat message-directory "drafts/")
748   "*Directory where Message autosaves buffers if Gnus isn't running.
749 If nil, Message won't autosave."
750   :group 'message-buffers
751   :type 'directory)
752
753 ;;; Internal variables.
754 ;;; Well, not really internal.
755
756 (defvar message-mode-syntax-table
757   (let ((table (copy-syntax-table text-mode-syntax-table)))
758     (modify-syntax-entry ?% ". " table)
759     table)
760   "Syntax table used while in Message mode.")
761
762 (defvar message-mode-abbrev-table text-mode-abbrev-table
763   "Abbrev table used in Message mode buffers.
764 Defaults to `text-mode-abbrev-table'.")
765 (defgroup message-headers nil
766   "Message headers."
767   :link '(custom-manual "(message)Variables")
768   :group 'message)
769
770 (defface message-header-to-face
771   '((((class color)
772       (background dark))
773      (:foreground "green2" :bold t))
774     (((class color)
775       (background light))
776      (:foreground "MidnightBlue" :bold t))
777     (t
778      (:bold t :italic t)))
779   "Face used for displaying From headers."
780   :group 'message-faces)
781
782 (defface message-header-cc-face
783   '((((class color)
784       (background dark))
785      (:foreground "green4" :bold t))
786     (((class color)
787       (background light))
788      (:foreground "MidnightBlue"))
789     (t
790      (:bold t)))
791   "Face used for displaying Cc headers."
792   :group 'message-faces)
793
794 (defface message-header-subject-face
795   '((((class color)
796       (background dark))
797      (:foreground "green3"))
798     (((class color)
799       (background light))
800      (:foreground "navy blue" :bold t))
801     (t
802      (:bold t)))
803   "Face used for displaying subject headers."
804   :group 'message-faces)
805
806 (defface message-header-newsgroups-face
807   '((((class color)
808       (background dark))
809      (:foreground "yellow" :bold t :italic t))
810     (((class color)
811       (background light))
812      (:foreground "blue4" :bold t :italic t))
813     (t
814      (:bold t :italic t)))
815   "Face used for displaying newsgroups headers."
816   :group 'message-faces)
817
818 (defface message-header-other-face
819   '((((class color)
820       (background dark))
821      (:foreground "#b00000"))
822     (((class color)
823       (background light))
824      (:foreground "steel blue"))
825     (t
826      (:bold t :italic t)))
827   "Face used for displaying newsgroups headers."
828   :group 'message-faces)
829
830 (defface message-header-name-face
831   '((((class color)
832       (background dark))
833      (:foreground "DarkGreen"))
834     (((class color)
835       (background light))
836      (:foreground "cornflower blue"))
837     (t
838      (:bold t)))
839   "Face used for displaying header names."
840   :group 'message-faces)
841
842 (defface message-header-xheader-face
843   '((((class color)
844       (background dark))
845      (:foreground "blue"))
846     (((class color)
847       (background light))
848      (:foreground "blue"))
849     (t
850      (:bold t)))
851   "Face used for displaying X-Header headers."
852   :group 'message-faces)
853
854 (defface message-separator-face
855   '((((class color)
856       (background dark))
857      (:foreground "blue3"))
858     (((class color)
859       (background light))
860      (:foreground "brown"))
861     (t
862      (:bold t)))
863   "Face used for displaying the separator."
864   :group 'message-faces)
865
866 (defface message-cited-text-face
867   '((((class color)
868       (background dark))
869      (:foreground "red"))
870     (((class color)
871       (background light))
872      (:foreground "red"))
873     (t
874      (:bold t)))
875   "Face used for displaying cited text names."
876   :group 'message-faces)
877
878 (defvar message-font-lock-keywords
879   (let* ((cite-prefix "A-Za-z")
880          (cite-suffix (concat cite-prefix "0-9_.@-"))
881          (content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)"))
882     `((,(concat "^\\([Tt]o:\\)" content)
883        (1 'message-header-name-face)
884        (2 'message-header-to-face nil t))
885       (,(concat "^\\([GBF]?[Cc][Cc]:\\|[Rr]eply-[Tt]o:\\|"
886                 "[Mm]ail-[Cc]opies-[Tt]o:\\|"
887                 "[Mm]ail-[Rr]eply-[Tt]o:\\|"
888                 "[Mm]ail-[Ff]ollowup-[Tt]o:\\)" content)
889        (1 'message-header-name-face)
890        (2 'message-header-cc-face nil t))
891       (,(concat "^\\([Ss]ubject:\\)" content)
892        (1 'message-header-name-face)
893        (2 'message-header-subject-face nil t))
894       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
895        (1 'message-header-name-face)
896        (2 'message-header-newsgroups-face nil t))
897       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
898        (1 'message-header-name-face)
899        (2 'message-header-other-face nil t))
900       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
901        (1 'message-header-name-face)
902        (2 'message-header-name-face))
903       ,@(if (and mail-header-separator
904                  (not (equal mail-header-separator "")))
905             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
906                1 'message-separator-face))
907           nil)
908       (,(concat "^[ \t]*"
909                 "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
910                 "[:>|}].*")
911        (0 'message-cited-text-face))))
912   "Additional expressions to highlight in Message mode.")
913
914 ;; XEmacs does it like this.  For Emacs, we have to set the
915 ;; `font-lock-defaults' buffer-local variable.
916 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
917
918 (defvar message-face-alist
919   '((bold . bold-region)
920     (underline . underline-region)
921     (default . (lambda (b e)
922                  (unbold-region b e)
923                  (ununderline-region b e))))
924   "Alist of mail and news faces for facemenu.
925 The cdr of ech entry is a function for applying the face to a region.")
926
927 (defcustom message-send-hook nil
928   "Hook run before sending messages."
929   :group 'message-various
930   :options '(ispell-message)
931   :type 'hook)
932
933 (defcustom message-send-mail-hook nil
934   "Hook run before sending mail messages."
935   :group 'message-various
936   :type 'hook)
937
938 (defcustom message-send-news-hook nil
939   "Hook run before sending news messages."
940   :group 'message-various
941   :type 'hook)
942
943 (defcustom message-sent-hook nil
944   "Hook run after sending messages."
945   :group 'message-various
946   :type 'hook)
947
948 (defcustom message-use-multi-frames nil
949   "Make new frame when sending messages."
950   :group 'message-frames
951   :type 'boolean)
952
953 (defcustom message-delete-frame-on-exit nil
954   "Delete frame after sending messages."
955   :group 'message-frames
956   :type '(choice (const :tag "off" nil)
957                  (const :tag "always" t)
958                  (const :tag "ask" ask)))
959
960 (defvar message-send-coding-system 'binary
961   "Coding system to encode outgoing mail.")
962
963 ;;; Internal variables.
964
965 (defvar message-default-charset nil)
966 (defvar message-buffer-list nil)
967 (defvar message-this-is-news nil)
968 (defvar message-this-is-mail nil)
969 (defvar message-draft-article nil)
970
971 ;; Byte-compiler warning
972 (defvar gnus-active-hashtb)
973 (defvar gnus-read-active-file)
974
975 ;;; Regexp matching the delimiter of messages in UNIX mail format
976 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
977 ;;; of rmail.el's rmail-unix-mail-delimiter.
978 (defvar message-unix-mail-delimiter
979   (let ((time-zone-regexp
980          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
981                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
982                  "\\|"
983                  "\\) *")))
984     (concat
985      "From "
986
987      ;; Many things can happen to an RFC 822 mailbox before it is put into
988      ;; a `From' line.  The leading phrase can be stripped, e.g.
989      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
990      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
991      ;; can be removed, e.g.
992      ;;         From: joe@y.z (Joe      K
993      ;;                 User)
994      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
995      ;;         From: Joe User
996      ;;                 <joe@y.z>
997      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
998      ;; The mailbox can be removed or be replaced by white space, e.g.
999      ;;         From: "Joe User"{space}{tab}
1000      ;;                 <joe@y.z>
1001      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1002      ;; where {space} and {tab} represent the Ascii space and tab characters.
1003      ;; We want to match the results of any of these manglings.
1004      ;; The following regexp rejects names whose first characters are
1005      ;; obviously bogus, but after that anything goes.
1006      "\\([^\0-\b\n-\r\^?].*\\)? "
1007
1008      ;; The time the message was sent.
1009      "\\([^\0-\r \^?]+\\) +"                            ; day of the week
1010      "\\([^\0-\r \^?]+\\) +"                            ; month
1011      "\\([0-3]?[0-9]\\) +"                              ; day of month
1012      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"  ; time of day
1013
1014      ;; Perhaps a time zone, specified by an abbreviation, or by a
1015      ;; numeric offset.
1016      time-zone-regexp
1017
1018      ;; The year.
1019      " \\([0-9][0-9]+\\) *"
1020
1021      ;; On some systems the time zone can appear after the year, too.
1022      time-zone-regexp
1023
1024      ;; Old uucp cruft.
1025      "\\(remote from .*\\)?"
1026
1027      "\n"))
1028   "Regexp matching the delimiter of messages in UNIX mail format.")
1029
1030 (defvar message-unsent-separator
1031   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1032           "^ *---+ +Returned message +---+ *$\\|"
1033           "^Start of returned message$\\|"
1034           "^ *---+ +Original message +---+ *$\\|"
1035           "^ *--+ +begin message +--+ *$\\|"
1036           "^ *---+ +Original message follows +---+ *$\\|"
1037           "^|? *---+ +Message text follows: +---+ *|?$")
1038   "A regexp that matches the separator before the text of a failed message.")
1039
1040 (defvar message-header-format-alist
1041   `((Newsgroups)
1042     (To . message-fill-address)
1043     (Cc . message-fill-address)
1044     (Subject)
1045     (In-Reply-To)
1046     (Fcc)
1047     (Bcc)
1048     (Date)
1049     (Organization)
1050     (Distribution)
1051     (Lines)
1052     (Expires)
1053     (Message-ID)
1054     ;; (References . message-shorten-references)
1055     (References . message-fill-header)
1056     (User-Agent))
1057   "Alist used for formatting headers.")
1058
1059 (eval-and-compile
1060   (autoload 'message-setup-toolbar "messagexmas")
1061   (autoload 'mh-new-draft-name "mh-comp")
1062   (autoload 'mh-send-letter "mh-comp")
1063   (autoload 'gnus-point-at-eol "gnus-util")
1064   (autoload 'gnus-point-at-bol "gnus-util")
1065   (autoload 'gnus-output-to-mail "gnus-util")
1066   (autoload 'gnus-output-to-rmail "gnus-util")
1067   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1068   (autoload 'nndraft-request-associate-buffer "nndraft")
1069   (autoload 'nndraft-request-expire-articles "nndraft")
1070   (autoload 'gnus-open-server "gnus-int")
1071   (autoload 'gnus-request-post "gnus-int")
1072   (autoload 'gnus-copy-article-buffer "gnus-msg")
1073   (autoload 'gnus-alive-p "gnus-util")
1074   (autoload 'rmail-output "rmail"))
1075
1076 \f
1077
1078 ;;;
1079 ;;; Utility functions.
1080 ;;;
1081
1082 (defmacro message-y-or-n-p (question show &rest text)
1083   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1084   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1085
1086 ;; Delete the current line (and the next N lines.);
1087 (defmacro message-delete-line (&optional n)
1088   `(delete-region (progn (beginning-of-line) (point))
1089                   (progn (forward-line ,(or n 1)) (point))))
1090
1091 (defun message-tokenize-header (header &optional separator)
1092   "Split HEADER into a list of header elements.
1093 \",\" is used as the separator."
1094   (if (not header)
1095       nil
1096     (let ((regexp (format "[%s]+" (or separator ",")))
1097           (beg 1)
1098           (first t)
1099           quoted elems paren)
1100       (save-excursion
1101         (message-set-work-buffer)
1102         (insert header)
1103         (goto-char (point-min))
1104         (while (not (eobp))
1105           (if first
1106               (setq first nil)
1107             (forward-char 1))
1108           (cond ((and (> (point) beg)
1109                       (or (eobp)
1110                           (and (looking-at regexp)
1111                                (not quoted)
1112                                (not paren))))
1113                  (push (buffer-substring beg (point)) elems)
1114                  (setq beg (match-end 0)))
1115                 ((= (following-char) ?\")
1116                  (setq quoted (not quoted)))
1117                 ((and (= (following-char) ?\()
1118                       (not quoted))
1119                  (setq paren t))
1120                 ((and (= (following-char) ?\))
1121                       (not quoted))
1122                  (setq paren nil))))
1123         (nreverse elems)))))
1124
1125 (defun message-mail-file-mbox-p (file)
1126   "Say whether FILE looks like a Unix mbox file."
1127   (when (and (file-exists-p file)
1128              (file-readable-p file)
1129              (file-regular-p file))
1130     (with-temp-buffer
1131       (nnheader-insert-file-contents file)
1132       (goto-char (point-min))
1133       (looking-at message-unix-mail-delimiter))))
1134
1135 (defun message-fetch-field (header &optional not-all)
1136   "The same as `mail-fetch-field', only remove all newlines."
1137   (let* ((inhibit-point-motion-hooks t)
1138          (value (mail-fetch-field header nil (not not-all))))
1139     (when value
1140       (nnheader-replace-chars-in-string value ?\n ? ))))
1141
1142 (defun message-narrow-to-field ()
1143   "Narrow the buffer to the header on the current line."
1144   (beginning-of-line)
1145   (narrow-to-region
1146    (point)
1147    (progn
1148      (forward-line 1)
1149      (if (re-search-forward "^[^ \n\t]" nil t)
1150          (progn
1151            (beginning-of-line)
1152            (point))
1153        (point-max))))
1154   (goto-char (point-min)))
1155
1156 (defun message-add-header (&rest headers)
1157   "Add the HEADERS to the message header, skipping those already present."
1158   (while headers
1159     (let (hclean)
1160       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1161         (error "Invalid header `%s'" (car headers)))
1162       (setq hclean (match-string 1 (car headers)))
1163     (save-restriction
1164       (message-narrow-to-headers)
1165       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1166         (insert (car headers) ?\n))))
1167     (setq headers (cdr headers))))
1168
1169 (defun message-fetch-reply-field (header)
1170   "Fetch FIELD from the message we're replying to."
1171   (when (and message-reply-buffer
1172              (buffer-name message-reply-buffer))
1173     (save-excursion
1174       (set-buffer message-reply-buffer)
1175       (message-fetch-field header))))
1176
1177 (defun message-set-work-buffer ()
1178   (if (get-buffer " *message work*")
1179       (progn
1180         (set-buffer " *message work*")
1181         (erase-buffer))
1182     (set-buffer (get-buffer-create " *message work*"))
1183     (kill-all-local-variables)
1184     (buffer-disable-undo (current-buffer))))
1185
1186 (defun message-functionp (form)
1187   "Return non-nil if FORM is funcallable."
1188   (or (and (symbolp form) (fboundp form))
1189       (and (listp form) (eq (car form) 'lambda))
1190       (byte-code-function-p form)))
1191
1192 (defun message-strip-subject-re (subject)
1193   "Remove \"Re:\" from subject lines."
1194   (if (string-match message-subject-re-regexp subject)
1195       (substring subject (match-end 0))
1196     subject))
1197
1198 (defun message-remove-header (header &optional is-regexp first reverse)
1199   "Remove HEADER in the narrowed buffer.
1200 If REGEXP, HEADER is a regular expression.
1201 If FIRST, only remove the first instance of the header.
1202 Return the number of headers removed."
1203   (goto-char (point-min))
1204   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1205         (number 0)
1206         (case-fold-search t)
1207         last)
1208     (while (and (not (eobp))
1209                 (not last))
1210       (if (if reverse
1211               (not (looking-at regexp))
1212             (looking-at regexp))
1213           (progn
1214             (incf number)
1215             (when first
1216               (setq last t))
1217             (delete-region
1218              (point)
1219              ;; There might be a continuation header, so we have to search
1220              ;; until we find a new non-continuation line.
1221              (progn
1222                (forward-line 1)
1223                (if (re-search-forward "^[^ \t]" nil t)
1224                    (goto-char (match-beginning 0))
1225                  (point-max)))))
1226         (forward-line 1)
1227         (if (re-search-forward "^[^ \t]" nil t)
1228             (goto-char (match-beginning 0))
1229           (point-max))))
1230     number))
1231
1232 (defun message-narrow-to-headers ()
1233   "Narrow the buffer to the head of the message."
1234   (widen)
1235   (narrow-to-region
1236    (goto-char (point-min))
1237    (if (re-search-forward
1238         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1239        (match-beginning 0)
1240      (point-max)))
1241   (goto-char (point-min)))
1242
1243 (defun message-narrow-to-head ()
1244   "Narrow the buffer to the head of the message.
1245 Point is left at the beginning of the narrowed-to region."
1246   (widen)
1247   (narrow-to-region
1248    (goto-char (point-min))
1249    (if (search-forward "\n\n" nil 1)
1250        (1- (point))
1251      (point-max)))
1252   (goto-char (point-min)))
1253
1254 (defun message-news-p ()
1255   "Say whether the current buffer contains a news message."
1256   (and (not message-this-is-mail)
1257        (or message-this-is-news
1258            (save-excursion
1259              (save-restriction
1260                (message-narrow-to-headers)
1261                (and (message-fetch-field "newsgroups")
1262                     (not (message-fetch-field "posted-to"))))))))
1263
1264 (defun message-mail-p ()
1265   "Say whether the current buffer contains a mail message."
1266   (and (not message-this-is-news)
1267        (or message-this-is-mail
1268            (save-excursion
1269              (save-restriction
1270                (message-narrow-to-headers)
1271                (or (message-fetch-field "to")
1272                    (message-fetch-field "cc")
1273                    (message-fetch-field "bcc")))))))
1274
1275 (defun message-next-header ()
1276   "Go to the beginning of the next header."
1277   (beginning-of-line)
1278   (or (eobp) (forward-char 1))
1279   (not (if (re-search-forward "^[^ \t]" nil t)
1280            (beginning-of-line)
1281          (goto-char (point-max)))))
1282
1283 (defun message-sort-headers-1 ()
1284   "Sort the buffer as headers using `message-rank' text props."
1285   (goto-char (point-min))
1286   (sort-subr
1287    nil 'message-next-header
1288    (lambda ()
1289      (message-next-header)
1290      (unless (bobp)
1291        (forward-char -1)))
1292    (lambda ()
1293      (or (get-text-property (point) 'message-rank)
1294          10000))))
1295
1296 (defun message-sort-headers ()
1297   "Sort the headers of the current message according to `message-header-format-alist'."
1298   (interactive)
1299   (save-excursion
1300     (save-restriction
1301       (let ((max (1+ (length message-header-format-alist)))
1302             rank)
1303         (message-narrow-to-headers)
1304         (while (re-search-forward "^[^ \n]+:" nil t)
1305           (put-text-property
1306            (match-beginning 0) (1+ (match-beginning 0))
1307            'message-rank
1308            (if (setq rank (length (memq (assq (intern (buffer-substring
1309                                                        (match-beginning 0)
1310                                                        (1- (match-end 0))))
1311                                               message-header-format-alist)
1312                                         message-header-format-alist)))
1313                (- max rank)
1314              (1+ max)))))
1315       (message-sort-headers-1))))
1316
1317 \f
1318
1319 ;;;
1320 ;;; Message mode
1321 ;;;
1322
1323 ;;; Set up keymap.
1324
1325 (defvar message-mode-map nil)
1326
1327 (unless message-mode-map
1328   (setq message-mode-map (copy-keymap text-mode-map))
1329   (define-key message-mode-map "\C-c?" 'describe-mode)
1330
1331   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1332   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1333   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1334   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1335   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1336   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1337   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
1338   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1339   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1340   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1341   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1342   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1343   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1344   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1345   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1346
1347   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1348   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1349
1350   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1351   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1352   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1353   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1354   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1355   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1356
1357   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1358   (define-key message-mode-map "\C-c\C-s" 'message-send)
1359   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1360   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1361
1362   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1363   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1364   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1365   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1366
1367   (define-key message-mode-map "\t" 'message-tab))
1368
1369 (easy-menu-define
1370  message-mode-menu message-mode-map "Message Menu."
1371  '("Message"
1372    ["Sort Headers" message-sort-headers t]
1373    ["Yank Original" message-yank-original t]
1374    ["Fill Yanked Message" message-fill-yanked-message t]
1375    ["Insert Signature" message-insert-signature t]
1376    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1377    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1378    ["Elide Region" message-elide-region (mark t)]
1379    ["Delete Outside Region" message-delete-not-region (mark t)]
1380    ["Kill To Signature" message-kill-to-signature t]
1381    ["Newline and Reformat" message-newline-and-reformat t]
1382    ["Rename buffer" message-rename-buffer t]
1383    ["Spellcheck" ispell-message t]
1384    "----"
1385    ["Send Message" message-send-and-exit t]
1386    ["Abort Message" message-dont-send t]
1387    ["Kill Message" message-kill-buffer t]))
1388
1389 (easy-menu-define
1390  message-mode-field-menu message-mode-map ""
1391  '("Field"
1392    ["Fetch To" message-insert-to t]
1393    ["Fetch Newsgroups" message-insert-newsgroups t]
1394    "----"
1395    ["To" message-goto-to t]
1396    ["Subject" message-goto-subject t]
1397    ["Cc" message-goto-cc t]
1398    ["Reply-To" message-goto-reply-to t]
1399    ["Mail-Reply-To" message-goto-mail-reply-to t]
1400    ["Mail-Followup-To" message-goto-mail-followup-to t]
1401    ["Mail-Copies-To" message-goto-mail-copies-to t]
1402    ["Summary" message-goto-summary t]
1403    ["Keywords" message-goto-keywords t]
1404    ["Newsgroups" message-goto-newsgroups t]
1405    ["Followup-To" message-goto-followup-to t]
1406    ["Distribution" message-goto-distribution t]
1407    ["Body" message-goto-body t]
1408    ["Signature" message-goto-signature t]))
1409
1410 (defvar facemenu-add-face-function)
1411 (defvar facemenu-remove-face-function)
1412
1413 ;;;###autoload
1414 (defun message-mode ()
1415   "Major mode for editing mail and news to be sent.
1416 Like Text Mode but with these additional commands:
1417 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1418 C-c C-f  move to a header field (and create it if there isn't):
1419          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1420          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1421          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1422          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1423          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1424          C-c C-f C-m  move to Mail-Followup-To
1425          C-c C-f C-f  move to Followup-To
1426 C-c C-t  message-insert-to (add a To header to a news followup)
1427 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1428 C-c C-b  message-goto-body (move to beginning of message text).
1429 C-c C-i  message-goto-signature (move to the beginning of the signature).
1430 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1431 C-c C-y  message-yank-original (insert current message, if any).
1432 C-c C-q  message-fill-yanked-message (fill what was yanked).
1433 C-c C-e  message-elide-region (elide the text between point and mark).
1434 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1435 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1436   (interactive)
1437   (kill-all-local-variables)
1438   (make-local-variable 'message-reply-buffer)
1439   (setq message-reply-buffer nil)
1440   (make-local-variable 'message-send-actions) 
1441   (make-local-variable 'message-exit-actions) 
1442   (make-local-variable 'message-kill-actions)
1443   (make-local-variable 'message-postpone-actions)
1444   (make-local-variable 'message-draft-article)
1445   (make-local-hook 'kill-buffer-hook)
1446   (set-syntax-table message-mode-syntax-table)
1447   (use-local-map message-mode-map)
1448   (setq local-abbrev-table message-mode-abbrev-table)
1449   (setq major-mode 'message-mode)
1450   (setq mode-name "Message")
1451   (setq buffer-offer-save t)
1452   (make-local-variable 'facemenu-add-face-function)
1453   (make-local-variable 'facemenu-remove-face-function)
1454   (setq facemenu-add-face-function
1455         (lambda (face end)
1456           (let ((face-fun (cdr (assq face message-face-alist))))
1457             (if face-fun
1458                 (funcall face-fun (point) end)
1459               (error "Face %s not configured for %s mode" face mode-name)))
1460           "")
1461         facemenu-remove-face-function t)
1462   (make-local-variable 'paragraph-separate)
1463   (make-local-variable 'paragraph-start)
1464   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1465   ;; lines that delimit forwarded messages.
1466   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1467   ;; are also sometimes used and should be separators.
1468   (setq paragraph-start
1469         (concat (regexp-quote mail-header-separator)
1470                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1471                 "-- $\\|---+$\\|"
1472                 page-delimiter
1473                 ;;!!! Uhm... shurely this can't be right?
1474                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1475   (setq paragraph-separate paragraph-start)
1476   (make-local-variable 'message-reply-headers)
1477   (setq message-reply-headers nil)
1478   (make-local-variable 'message-user-agent)
1479   (make-local-variable 'message-post-method)
1480   (make-local-variable 'message-sent-message-via)
1481   (setq message-sent-message-via nil)
1482   (make-local-variable 'message-checksum)
1483   (setq message-checksum nil)
1484   ;;(when (fboundp 'mail-hist-define-keys)
1485   ;;  (mail-hist-define-keys))
1486   (when (string-match "XEmacs\\|Lucid" emacs-version)
1487     (message-setup-toolbar))
1488   (easy-menu-add message-mode-menu message-mode-map)
1489   (easy-menu-add message-mode-field-menu message-mode-map)
1490   ;; Allow mail alias things.
1491   (when (eq message-mail-alias-type 'abbrev)
1492     (if (fboundp 'mail-abbrevs-setup)
1493         (mail-abbrevs-setup)
1494       (mail-aliases-setup)))
1495   (message-set-auto-save-file-name)
1496   (unless (string-match "XEmacs" emacs-version)
1497     (set (make-local-variable 'font-lock-defaults)
1498          '(message-font-lock-keywords t)))
1499   (make-local-variable 'adaptive-fill-regexp)
1500   (setq adaptive-fill-regexp
1501         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1502   (unless (boundp 'adaptive-fill-first-line-regexp)
1503     (setq adaptive-fill-first-line-regexp nil))
1504   (make-local-variable 'adaptive-fill-first-line-regexp)
1505   (setq adaptive-fill-first-line-regexp
1506         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1507                 adaptive-fill-first-line-regexp))
1508   (when (fboundp 'set-buffer-multibyte)
1509     (set-buffer-multibyte t))
1510   (run-hooks 'text-mode-hook 'message-mode-hook))
1511
1512 \f
1513
1514 ;;;
1515 ;;; Message mode commands
1516 ;;;
1517
1518 ;;; Movement commands
1519
1520 (defun message-goto-to ()
1521   "Move point to the To header."
1522   (interactive)
1523   (message-position-on-field "To"))
1524
1525 (defun message-goto-subject ()
1526   "Move point to the Subject header."
1527   (interactive)
1528   (message-position-on-field "Subject"))
1529
1530 (defun message-goto-cc ()
1531   "Move point to the Cc header."
1532   (interactive)
1533   (message-position-on-field "Cc" "To"))
1534
1535 (defun message-goto-bcc ()
1536   "Move point to the Bcc  header."
1537   (interactive)
1538   (message-position-on-field "Bcc" "Cc" "To"))
1539
1540 (defun message-goto-fcc ()
1541   "Move point to the Fcc header."
1542   (interactive)
1543   (message-position-on-field "Fcc" "To" "Newsgroups"))
1544
1545 (defun message-goto-reply-to ()
1546   "Move point to the Reply-To header."
1547   (interactive)
1548   (message-position-on-field "Reply-To" "Subject"))
1549
1550 (defun message-goto-mail-reply-to ()
1551   "Move point to the Mail-Reply-To header."
1552   (interactive)
1553   (message-position-on-field "Mail-Reply-To" "Subject"))
1554
1555 (defun message-goto-mail-followup-to ()
1556   "Move point to the Mail-Followup-To header."
1557   (interactive)
1558   (message-position-on-field "Mail-Followup-To" "Subject"))
1559
1560 (defun message-goto-mail-copies-to ()
1561   "Move point to the Mail-Copies-To header."
1562   (interactive)
1563   (message-position-on-field "Mail-Copies-To" "Subject"))
1564
1565 (defun message-goto-newsgroups ()
1566   "Move point to the Newsgroups header."
1567   (interactive)
1568   (message-position-on-field "Newsgroups"))
1569
1570 (defun message-goto-distribution ()
1571   "Move point to the Distribution header."
1572   (interactive)
1573   (message-position-on-field "Distribution"))
1574
1575 (defun message-goto-followup-to ()
1576   "Move point to the Followup-To header."
1577   (interactive)
1578   (message-position-on-field "Followup-To" "Newsgroups"))
1579
1580 (defun message-goto-keywords ()
1581   "Move point to the Keywords header."
1582   (interactive)
1583   (message-position-on-field "Keywords" "Subject"))
1584
1585 (defun message-goto-summary ()
1586   "Move point to the Summary header."
1587   (interactive)
1588   (message-position-on-field "Summary" "Subject"))
1589
1590 (defun message-goto-body ()
1591   "Move point to the beginning of the message body."
1592   (interactive)
1593   (if (looking-at "[ \t]*\n") (expand-abbrev))
1594   (goto-char (point-min))
1595   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1596
1597 (defun message-goto-eoh ()
1598   "Move point to the end of the headers."
1599   (interactive)
1600   (message-goto-body)
1601   (forward-line -2))
1602
1603 (defun message-goto-signature ()
1604   "Move point to the beginning of the message signature.
1605 If there is no signature in the article, go to the end and
1606 return nil."
1607   (interactive)
1608   (goto-char (point-min))
1609   (if (re-search-forward message-signature-separator nil t)
1610       (forward-line 1)
1611     (goto-char (point-max))
1612     nil))
1613
1614 \f
1615
1616 (defun message-insert-to (&optional force)
1617   "Insert a To header that points to the author of the article being replied to.
1618 If the original author requested not to be sent mail, the function signals
1619 an error.
1620 With the prefix argument FORCE, insert the header anyway."
1621   (interactive "P")
1622   (let ((co (message-fetch-reply-field "mail-copies-to")))
1623     (when (and (null force)
1624                co
1625                (equal (downcase co) "never"))
1626       (error "The user has requested not to have copies sent via mail")))
1627   (when (and (message-position-on-field "To")
1628              (mail-fetch-field "to")
1629              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1630     (insert ", "))
1631   (insert (or (message-fetch-reply-field "reply-to")
1632               (message-fetch-reply-field "from") "")))
1633
1634 (defun message-insert-newsgroups ()
1635   "Insert the Newsgroups header from the article being replied to."
1636   (interactive)
1637   (when (and (message-position-on-field "Newsgroups")
1638              (mail-fetch-field "newsgroups")
1639              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1640     (insert ","))
1641   (insert (or (message-fetch-reply-field "newsgroups") "")))
1642
1643 \f
1644
1645 ;;; Various commands
1646
1647 (defun message-delete-not-region (beg end)
1648   "Delete everything in the body of the current message that is outside of the region."
1649   (interactive "r")
1650   (save-excursion
1651     (goto-char end)
1652     (delete-region (point) (if (not (message-goto-signature))
1653                                (point)
1654                              (forward-line -2)
1655                              (point)))
1656     (insert "\n")
1657     (goto-char beg)
1658     (delete-region beg (progn (message-goto-body)
1659                               (forward-line 2)
1660                               (point))))
1661   (when (message-goto-signature)
1662     (forward-line -2)))
1663
1664 (defun message-kill-to-signature ()
1665   "Deletes all text up to the signature."
1666   (interactive)
1667   (let ((point (point)))
1668     (message-goto-signature)
1669     (unless (eobp)
1670       (forward-line -2))
1671     (kill-region point (point))
1672     (unless (bolp)
1673       (insert "\n"))))
1674
1675 (defun message-newline-and-reformat ()
1676   "Insert four newlines, and then reformat if inside quoted text."
1677   (interactive)
1678   (let ((point (point))
1679         quoted)
1680     (save-excursion
1681       (beginning-of-line)
1682       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1683     (insert "\n\n\n\n")
1684     (when quoted
1685       (insert message-yank-prefix))
1686     (fill-paragraph nil)
1687     (goto-char point)
1688     (forward-line 2)))
1689
1690 (defun message-insert-signature (&optional force)
1691   "Insert a signature.  See documentation for the `message-signature' variable."
1692   (interactive (list 0))
1693   (let* ((signature
1694           (cond
1695            ((and (null message-signature)
1696                  (eq force 0))
1697             (save-excursion
1698               (goto-char (point-max))
1699               (not (re-search-backward
1700                     message-signature-separator nil t))))
1701            ((and (null message-signature)
1702                  force)
1703             t)
1704            ((message-functionp message-signature)
1705             (funcall message-signature))
1706            ((listp message-signature)
1707             (eval message-signature))
1708            (t message-signature)))
1709          (signature
1710           (cond ((stringp signature)
1711                  signature)
1712                 ((and (eq t signature)
1713                       message-signature-file
1714                       (file-exists-p message-signature-file))
1715                  signature))))
1716     (when signature
1717       (goto-char (point-max))
1718       ;; Insert the signature.
1719       (unless (bolp)
1720         (insert "\n"))
1721       (insert "\n-- \n")
1722       (if (eq signature t)
1723           (insert-file-contents message-signature-file)
1724         (insert signature))
1725       (goto-char (point-max))
1726       (or (bolp) (insert "\n")))))
1727
1728 (defun message-elide-region (b e)
1729   "Elide the text between point and mark.
1730 An ellipsis (from `message-elide-elipsis') will be inserted where the
1731 text was killed."
1732   (interactive "r")
1733   (kill-region b e)
1734   (unless (bolp)
1735     (insert "\n"))
1736   (insert message-elide-elipsis))
1737
1738 (defvar message-caesar-translation-table nil)
1739
1740 (defun message-caesar-region (b e &optional n)
1741   "Caesar rotation of region by N, default 13, for decrypting netnews."
1742   (interactive
1743    (list
1744     (min (point) (or (mark t) (point)))
1745     (max (point) (or (mark t) (point)))
1746     (when current-prefix-arg
1747       (prefix-numeric-value current-prefix-arg))))
1748
1749   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1750   (unless (or (zerop n)                 ; no action needed for a rot of 0
1751               (= b e))                  ; no region to rotate
1752     ;; We build the table, if necessary.
1753     (when (or (not message-caesar-translation-table)
1754               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1755         (setq message-caesar-translation-table
1756               (message-make-caesar-translation-table n)))
1757     ;; Then we translate the region.  Do it this way to retain
1758     ;; text properties.
1759     (while (< b e)
1760       (subst-char-in-region
1761        b (1+ b) (char-after b)
1762        (aref message-caesar-translation-table (char-after b)))
1763       (incf b))))
1764
1765 (defun message-make-caesar-translation-table (n)
1766   "Create a rot table with offset N."
1767   (let ((i -1)
1768         (table (make-string 256 0)))
1769     (while (< (incf i) 256)
1770       (aset table i i))
1771     (concat
1772      (substring table 0 ?A)
1773      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1774      (substring table ?A (+ ?A n))
1775      (substring table (+ ?A 26) ?a)
1776      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1777      (substring table ?a (+ ?a n))
1778      (substring table (+ ?a 26) 255))))
1779
1780 (defun message-caesar-buffer-body (&optional rotnum)
1781   "Caesar rotates all letters in the current buffer by 13 places.
1782 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1783 With prefix arg, specifies the number of places to rotate each letter forward.
1784 Mail and USENET news headers are not rotated."
1785   (interactive (if current-prefix-arg
1786                    (list (prefix-numeric-value current-prefix-arg))
1787                  (list nil)))
1788   (save-excursion
1789     (save-restriction
1790       (when (message-goto-body)
1791         (narrow-to-region (point) (point-max)))
1792       (message-caesar-region (point-min) (point-max) rotnum))))
1793
1794 (defun message-pipe-buffer-body (program)
1795   "Pipe the message body in the current buffer through PROGRAM."
1796   (save-excursion
1797     (save-restriction
1798       (when (message-goto-body)
1799         (narrow-to-region (point) (point-max)))
1800       (let ((body (buffer-substring (point-min) (point-max))))
1801         (unless (equal 0 (call-process-region
1802                            (point-min) (point-max) program t t))
1803             (insert body)
1804             (message "%s failed." program))))))
1805
1806 (defun message-rename-buffer (&optional enter-string)
1807   "Rename the *message* buffer to \"*message* RECIPIENT\".
1808 If the function is run with a prefix, it will ask for a new buffer
1809 name, rather than giving an automatic name."
1810   (interactive "Pbuffer name: ")
1811   (save-excursion
1812     (save-restriction
1813       (goto-char (point-min))
1814       (narrow-to-region (point)
1815                         (search-forward mail-header-separator nil 'end))
1816       (let* ((mail-to (or
1817                        (if (message-news-p) (message-fetch-field "Newsgroups")
1818                          (message-fetch-field "To"))
1819                        ""))
1820              (mail-trimmed-to
1821               (if (string-match "," mail-to)
1822                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1823                 mail-to))
1824              (name-default (concat "*message* " mail-trimmed-to))
1825              (name (if enter-string
1826                        (read-string "New buffer name: " name-default)
1827                      name-default)))
1828         (rename-buffer name t)))))
1829
1830 (defun message-fill-yanked-message (&optional justifyp)
1831   "Fill the paragraphs of a message yanked into this one.
1832 Numeric argument means justify as well."
1833   (interactive "P")
1834   (save-excursion
1835     (goto-char (point-min))
1836     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1837     (let ((fill-prefix message-yank-prefix))
1838       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1839
1840 (defun message-indent-citation ()
1841   "Modify text just inserted from a message to be cited.
1842 The inserted text should be the region.
1843 When this function returns, the region is again around the modified text.
1844
1845 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1846 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1847   (let ((start (point)))
1848     ;; Remove unwanted headers.
1849     (when message-ignored-cited-headers
1850       (let (all-removed)
1851         (save-restriction
1852           (narrow-to-region
1853            (goto-char start)
1854            (if (search-forward "\n\n" nil t)
1855                (1- (point))
1856              (point)))
1857           (message-remove-header message-ignored-cited-headers t)
1858           (when (= (point-min) (point-max))
1859             (setq all-removed t))
1860           (goto-char (point-max)))
1861         (if all-removed
1862             (goto-char start)
1863           (forward-line 1))))
1864     ;; Delete blank lines at the start of the buffer.
1865     (while (and (point-min)
1866                 (eolp)
1867                 (not (eobp)))
1868       (message-delete-line))
1869     ;; Delete blank lines at the end of the buffer.
1870     (goto-char (point-max))
1871     (unless (eolp)
1872       (insert "\n"))
1873     (while (and (zerop (forward-line -1))
1874                 (looking-at "$"))
1875       (message-delete-line))
1876     ;; Do the indentation.
1877     (if (null message-yank-prefix)
1878         (indent-rigidly start (mark t) message-indentation-spaces)
1879       (save-excursion
1880         (goto-char start)
1881         (while (< (point) (mark t))
1882           (insert message-yank-prefix)
1883           (forward-line 1))))
1884     (goto-char start)))
1885
1886 (defvar gnus-article-copy)
1887 (defun message-yank-original (&optional arg)
1888   "Insert the message being replied to, if any.
1889 Puts point before the text and mark after.
1890 Normally indents each nonblank line ARG spaces (default 3).  However,
1891 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1892
1893 This function uses `message-cite-function' to do the actual citing.
1894
1895 Just \\[universal-argument] as argument means don't indent, insert no
1896 prefix, and don't delete any headers."
1897   (interactive "P")
1898   (let ((modified (buffer-modified-p)))
1899     (when (and message-reply-buffer
1900                message-cite-function)
1901       (gnus-copy-article-buffer)
1902       (setq message-reply-buffer gnus-article-copy)
1903       (delete-windows-on message-reply-buffer t)
1904       (insert-buffer message-reply-buffer)
1905       (funcall message-cite-function)
1906       (message-exchange-point-and-mark)
1907       (unless (bolp)
1908         (insert ?\n))
1909       (unless modified
1910         (setq message-checksum (message-checksum))))))
1911
1912 (defun message-cite-original-without-signature ()
1913   "Cite function in the standard Message manner."
1914   (let ((start (point))
1915         (end (mark t))
1916         (functions
1917          (when message-indent-citation-function
1918            (if (listp message-indent-citation-function)
1919                message-indent-citation-function
1920              (list message-indent-citation-function)))))
1921     (goto-char end)
1922     (when (re-search-backward "^-- $" start t)
1923       ;; Also peel off any blank lines before the signature.
1924       (forward-line -1)
1925       (while (looking-at "^[ \t]*$")
1926         (forward-line -1))
1927       (forward-line 1)
1928       (delete-region (point) end))
1929     (goto-char start)
1930     (while functions
1931       (funcall (pop functions)))
1932     (when message-citation-line-function
1933       (unless (bolp)
1934         (insert "\n"))
1935       (funcall message-citation-line-function))))
1936
1937 (defvar mail-citation-hook) ;Compiler directive
1938 (defun message-cite-original ()
1939   "Cite function in the standard Message manner."
1940   (if (and (boundp 'mail-citation-hook)
1941            mail-citation-hook)
1942       (run-hooks 'mail-citation-hook)
1943     (let ((start (point))
1944           (functions
1945            (when message-indent-citation-function
1946              (if (listp message-indent-citation-function)
1947                  message-indent-citation-function
1948                (list message-indent-citation-function)))))
1949       (goto-char start)
1950       (while functions
1951         (funcall (pop functions)))
1952       (when message-citation-line-function
1953         (unless (bolp)
1954           (insert "\n"))
1955         (funcall message-citation-line-function)))))
1956
1957 (defun message-insert-citation-line ()
1958   "Function that inserts a simple citation line."
1959   (when message-reply-headers
1960     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1961
1962 (defun message-position-on-field (header &rest afters)
1963   (let ((case-fold-search t))
1964     (save-restriction
1965       (narrow-to-region
1966        (goto-char (point-min))
1967        (progn
1968          (re-search-forward
1969           (concat "^" (regexp-quote mail-header-separator) "$"))
1970          (match-beginning 0)))
1971       (goto-char (point-min))
1972       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1973           (progn
1974             (re-search-forward "^[^ \t]" nil 'move)
1975             (beginning-of-line)
1976             (skip-chars-backward "\n")
1977             t)
1978         (while (and afters
1979                     (not (re-search-forward
1980                           (concat "^" (regexp-quote (car afters)) ":")
1981                           nil t)))
1982           (pop afters))
1983         (when afters
1984           (re-search-forward "^[^ \t]" nil 'move)
1985           (beginning-of-line))
1986         (insert header ": \n")
1987         (forward-char -1)
1988         nil))))
1989
1990 (defun message-remove-signature ()
1991   "Remove the signature from the text between point and mark.
1992 The text will also be indented the normal way."
1993   (save-excursion
1994     (let ((start (point))
1995           mark)
1996       (if (not (re-search-forward message-signature-separator (mark t) t))
1997           ;; No signature here, so we just indent the cited text.
1998           (message-indent-citation)
1999         ;; Find the last non-empty line.
2000         (forward-line -1)
2001         (while (looking-at "[ \t]*$")
2002           (forward-line -1))
2003         (forward-line 1)
2004         (setq mark (set-marker (make-marker) (point)))
2005         (goto-char start)
2006         (message-indent-citation)
2007         ;; Enable undoing the deletion.
2008         (undo-boundary)
2009         (delete-region mark (mark t))
2010         (set-marker mark nil)))))
2011
2012 \f
2013
2014 ;;;
2015 ;;; Sending messages
2016 ;;;
2017
2018 ;; Avoid byte-compile warning.
2019 (defvar message-encoding-buffer nil)
2020 (defvar message-edit-buffer nil)
2021 (defvar message-mime-mode nil)
2022
2023 (defun message-send-and-exit (&optional arg)
2024   "Send message like `message-send', then, if no errors, exit from mail buffer."
2025   (interactive "P")
2026   (let ((buf (current-buffer))
2027         (actions message-exit-actions)
2028         (frame (selected-frame))
2029         (org-frame message-original-frame))
2030     (when (and (message-send arg)
2031                (buffer-name buf))
2032       (if message-kill-buffer-on-exit
2033           (kill-buffer buf)
2034         (bury-buffer buf)
2035         (when (eq buf (current-buffer))
2036           (message-bury buf)))
2037       (message-do-actions actions)
2038       (message-delete-frame frame org-frame))))
2039
2040 (defun message-dont-send ()
2041   "Don't send the message you have been editing."
2042   (interactive)
2043   (set-buffer-modified-p t)
2044   (save-buffer)
2045   (let ((actions message-postpone-actions))
2046     (message-bury (current-buffer))
2047     (message-do-actions actions)))
2048
2049 (defun message-kill-buffer ()
2050   "Kill the current buffer."
2051   (interactive)
2052   (when (or (not (buffer-modified-p))
2053             (yes-or-no-p "Message modified; kill anyway? "))
2054     (let ((actions message-kill-actions)
2055           (frame (selected-frame))
2056           (org-frame message-original-frame))
2057       (setq buffer-file-name nil)
2058       (kill-buffer (current-buffer))
2059       (message-do-actions actions)
2060       (message-delete-frame frame org-frame))))
2061
2062 (defun message-delete-frame (frame org-frame)
2063   "Delete frame for editing message."
2064   (when (and (or (and (featurep 'xemacs)
2065                       (not (eq 'tty (device-type))))
2066                  window-system
2067                  (>= emacs-major-version 20))
2068              (or (and (eq message-delete-frame-on-exit t)
2069                       (select-frame frame)
2070                       (or (eq frame org-frame)
2071                           (prog1
2072                               (y-or-n-p "Delete this frame?")
2073                             (message ""))))
2074                  (and (eq message-delete-frame-on-exit 'ask)
2075                       (select-frame frame)
2076                       (prog1
2077                           (y-or-n-p "Delete this frame?")
2078                         (message "")))))
2079     (delete-frame frame)))
2080
2081 (defun message-bury (buffer)
2082   "Bury this mail buffer."
2083   (let ((newbuf (other-buffer buffer)))
2084     (bury-buffer buffer)
2085     (if (and (fboundp 'frame-parameters)
2086              (cdr (assq 'dedicated (frame-parameters)))
2087              (not (null (delq (selected-frame) (visible-frame-list)))))
2088         (delete-frame (selected-frame))
2089       (switch-to-buffer newbuf))))
2090
2091 (defun message-send (&optional arg)
2092   "Send the message in the current buffer.
2093 If `message-interactive' is non-nil, wait for success indication
2094 or error messages, and inform user.
2095 Otherwise any failure is reported in a message back to
2096 the user from the mailer."
2097   (interactive "P")
2098   ;; Disabled test.
2099   (when (or (buffer-modified-p)
2100             (message-check-element 'unchanged)
2101             (y-or-n-p "No changes in the buffer; really send? "))
2102     ;; Make it possible to undo the coming changes.
2103     (undo-boundary)
2104     (let ((inhibit-read-only t))
2105       (put-text-property (point-min) (point-max) 'read-only nil))
2106     (message-fix-before-sending)
2107     (run-hooks 'message-send-hook)
2108     (message "Sending...")
2109     (let ((message-encoding-buffer
2110            (message-generate-new-buffer-clone-locals " message encoding"))
2111           (message-edit-buffer (current-buffer))
2112           (message-mime-mode mime-edit-mode-flag)
2113           (alist message-send-method-alist)
2114           (success t)
2115           elem sent)
2116       (save-excursion
2117         (set-buffer message-encoding-buffer)
2118         (erase-buffer)
2119         (insert-buffer message-edit-buffer)
2120         (funcall message-encode-function)
2121         (while (and success
2122                     (setq elem (pop alist)))
2123           (when (and (or (not (funcall (cadr elem)))
2124                          (and (or (not (memq (car elem)
2125                                              message-sent-message-via))
2126                                   (y-or-n-p
2127                                    (format
2128                                     "Already sent message via %s; resend? "
2129                                     (car elem))))
2130                               (setq success (funcall (caddr elem) arg)))))
2131             (setq sent t))))
2132       (when (and success sent)
2133         (message-do-fcc)
2134         ;;(when (fboundp 'mail-hist-put-headers-into-history)
2135         ;; (mail-hist-put-headers-into-history))
2136         (run-hooks 'message-sent-hook)
2137         (message "Sending...done")
2138         ;; Mark the buffer as unmodified and delete autosave.
2139         (set-buffer-modified-p nil)
2140         (delete-auto-save-file-if-necessary t)
2141         (message-disassociate-draft)
2142         ;; Delete other mail buffers and stuff.
2143         (message-do-send-housekeeping)
2144         (message-do-actions message-send-actions)
2145         ;; Return success.
2146         t))))
2147
2148 (defun message-send-via-mail (arg)
2149   "Send the current message via mail."
2150   (message-send-mail arg))
2151
2152 (defun message-send-via-news (arg)
2153   "Send the current message via news."
2154   (message-send-news arg))
2155
2156 (defun message-fix-before-sending ()
2157   "Do various things to make the message nice before sending it."
2158   ;; Make sure there's a newline at the end of the message.
2159   (goto-char (point-max))
2160   (unless (bolp)
2161     (insert "\n"))
2162   ;; Delete all invisible text.
2163   (when (text-property-any (point-min) (point-max) 'invisible t)
2164     (put-text-property (point-min) (point-max) 'invisible nil)
2165     (unless (yes-or-no-p "Invisible text found and made visible; continue posting?")
2166       (error "Invisible text found and made visible"))))
2167
2168 (defun message-add-action (action &rest types)
2169   "Add ACTION to be performed when doing an exit of type TYPES."
2170   (let (var)
2171     (while types
2172       (set (setq var (intern (format "message-%s-actions" (pop types))))
2173            (nconc (symbol-value var) (list action))))))
2174
2175 (defun message-do-actions (actions)
2176   "Perform all actions in ACTIONS."
2177   ;; Now perform actions on successful sending.
2178   (while actions
2179     (ignore-errors
2180       (cond
2181        ;; A simple function.
2182        ((message-functionp (car actions))
2183         (funcall (car actions)))
2184        ;; Something to be evaled.
2185        (t
2186         (eval (car actions)))))
2187     (pop actions)))
2188
2189 (defun message-send-mail (&optional arg)
2190   (require 'mail-utils)
2191   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2192         (case-fold-search nil)
2193         (news (message-news-p)))
2194     (save-restriction
2195       (message-narrow-to-headers)
2196       ;; Insert some headers.
2197       (let ((message-deletable-headers
2198              (if news nil message-deletable-headers)))
2199         (message-generate-headers message-required-mail-headers))
2200       ;; Let the user do all of the above.
2201       (run-hooks 'message-header-hook))
2202     (unwind-protect
2203         (save-excursion
2204           (set-buffer tembuf)
2205           (erase-buffer)
2206           (insert-buffer message-encoding-buffer)
2207           ;; Remove some headers.
2208           (save-restriction
2209             (message-narrow-to-headers)
2210             ;; Remove some headers.
2211             (message-remove-header message-ignored-mail-headers t))
2212           (goto-char (point-max))
2213           ;; require one newline at the end.
2214           (or (= (preceding-char) ?\n)
2215               (insert ?\n))
2216           (when (and news
2217                      (or (message-fetch-field "cc")
2218                          (message-fetch-field "to")))
2219             (message-insert-courtesy-copy))
2220           (mime-edit-maybe-split-and-send
2221            (function
2222             (lambda ()
2223               (interactive)
2224               (funcall message-send-mail-function)
2225               )))
2226           (funcall message-send-mail-function))
2227       (kill-buffer tembuf))
2228     (set-buffer message-edit-buffer)
2229     (push 'mail message-sent-message-via)))
2230
2231 (defun message-send-mail-with-sendmail ()
2232   "Send off the prepared buffer with sendmail."
2233   (let ((errbuf (if message-interactive
2234                     (generate-new-buffer " sendmail errors")
2235                   0))
2236         resend-addresses delimline)
2237     (let ((case-fold-search t))
2238       (save-restriction
2239         (message-narrow-to-headers)
2240         ;; XXX: We need to handle Resent-CC/Resent-BCC, too.
2241         (setq resend-addresses (message-fetch-field "resent-to")))
2242       ;; Change header-delimiter to be what sendmail expects.
2243       (goto-char (point-min))
2244       (re-search-forward
2245        (concat "^" (regexp-quote mail-header-separator) "\n"))
2246       (replace-match "\n")
2247       (backward-char 1)
2248       (setq delimline (point-marker))
2249       (run-hooks 'message-send-mail-hook)
2250       ;; Insert an extra newline if we need it to work around
2251       ;; Sun's bug that swallows newlines.
2252       (goto-char (1+ delimline))
2253       (when (eval message-mailer-swallows-blank-line)
2254         (newline))
2255       (when message-interactive
2256         (save-excursion
2257           (set-buffer errbuf)
2258           (erase-buffer))))
2259     (let ((default-directory "/")
2260           (coding-system-for-write message-send-coding-system))
2261       (apply 'call-process-region
2262              (append (list (point-min) (point-max)
2263                            (if (boundp 'sendmail-program)
2264                                sendmail-program
2265                              "/usr/lib/sendmail")
2266                            nil errbuf nil "-oi")
2267                      ;; Always specify who from,
2268                      ;; since some systems have broken sendmails.
2269                      ;; But some systems are more broken with -f, so
2270                      ;; we'll let users override this.
2271                      (if (null message-sendmail-f-is-evil)
2272                          (list "-f" (user-login-name)))
2273                      ;; These mean "report errors by mail"
2274                      ;; and "deliver in background".
2275                      (if (null message-interactive) '("-oem" "-odb"))
2276                      ;; Get the addresses from the message
2277                      ;; unless this is a resend.
2278                      ;; We must not do that for a resend
2279                      ;; because we would find the original addresses.
2280                      ;; For a resend, include the specific addresses.
2281                      (if resend-addresses
2282                          (list resend-addresses)
2283                        '("-t")))))
2284     (when message-interactive
2285       (save-excursion
2286         (set-buffer errbuf)
2287         (goto-char (point-min))
2288         (while (re-search-forward "\n\n* *" nil t)
2289           (replace-match "; "))
2290         (if (not (zerop (buffer-size)))
2291             (error "Sending...failed to %s"
2292                    (buffer-substring (point-min) (point-max)))))
2293       (when (bufferp errbuf)
2294         (kill-buffer errbuf)))))
2295
2296 (defun message-send-mail-with-qmail ()
2297   "Pass the prepared message buffer to qmail-inject.
2298 Refer to the documentation for the variable `message-send-mail-function'
2299 to find out how to use this."
2300   ;; replace the header delimiter with a blank line.
2301   (goto-char (point-min))
2302   (re-search-forward
2303    (concat "^" (regexp-quote mail-header-separator) "\n"))
2304   (replace-match "\n")
2305   (backward-char 1)
2306   (run-hooks 'message-send-mail-hook)
2307   ;; send the message
2308   (case
2309       (let ((coding-system-for-write message-send-coding-system))
2310         (apply
2311          'call-process-region 1 (point-max) message-qmail-inject-program
2312          nil nil nil
2313          ;; qmail-inject's default behaviour is to look for addresses on the
2314          ;; command line; if there're none, it scans the headers.
2315          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2316          ;;
2317          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2318          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2319          ;; message from stdin.
2320          ;;
2321          ;; qmail also has the advantage of not having been raped by
2322          ;; various vendors, so we don't have to allow for that, either --
2323          ;; compare this with message-send-mail-with-sendmail and weep
2324          ;; for sendmail's lost innocence.
2325          ;;
2326          ;; all this is way cool coz it lets us keep the arguments entirely
2327          ;; free for -inject-arguments -- a big win for the user and for us
2328          ;; since we don't have to play that double-guessing game and the user
2329          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2330          message-qmail-inject-args))
2331     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2332     ;; we have to look at the retval instead
2333     (0 nil)
2334     (1   (error "qmail-inject reported permanent failure"))
2335     (111 (error "qmail-inject reported transient failure"))
2336     ;; should never happen
2337     (t   (error "qmail-inject reported unknown failure"))))
2338
2339 (defun message-send-mail-with-mh ()
2340   "Send the prepared message buffer with mh."
2341   (let ((mh-previous-window-config nil)
2342         (name (mh-new-draft-name)))
2343     (setq buffer-file-name name)
2344     ;; MH wants to generate these headers itself.
2345     (when message-mh-deletable-headers
2346       (let ((headers message-mh-deletable-headers))
2347         (while headers
2348           (goto-char (point-min))
2349           (and (re-search-forward
2350                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2351                (message-delete-line))
2352           (pop headers))))
2353     (run-hooks 'message-send-mail-hook)
2354     ;; Pass it on to mh.
2355     (mh-send-letter)))
2356
2357 (defun message-send-mail-with-smtp ()
2358   "Send off the prepared buffer with SMTP."
2359   (require 'smtp) ; XXX
2360   (let ((case-fold-search t)
2361         recipients)
2362     (save-restriction
2363       (message-narrow-to-headers)
2364       (setq recipients
2365             ;; XXX: Should be replaced by better one.
2366             (smtp-deduce-address-list (current-buffer)
2367                                       (point-min) (point-max)))
2368       ;; Remove BCC lines.
2369       (message-remove-header "bcc"))
2370     ;; replace the header delimiter with a blank line.
2371     (goto-char (point-min))
2372     (re-search-forward
2373      (concat "^" (regexp-quote mail-header-separator) "\n"))
2374     (replace-match "\n")
2375     (backward-char 1)
2376     (run-hooks 'message-send-mail-hook)
2377     (if recipients
2378         (let ((result (smtp-via-smtp user-mail-address
2379                                      recipients
2380                                      (current-buffer))))
2381           (unless (eq result t)
2382             (error "Sending failed; " result)))
2383       (error "Sending failed; no recipients"))))
2384
2385 (defun message-send-news (&optional arg)
2386   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2387         (case-fold-search nil)
2388         (method (if (message-functionp message-post-method)
2389                     (funcall message-post-method arg)
2390                   message-post-method))
2391         (message-syntax-checks
2392          (if arg
2393              (cons '(existing-newsgroups . disabled)
2394                    message-syntax-checks)
2395            message-syntax-checks))
2396         result)
2397     (save-restriction
2398       (message-narrow-to-headers)
2399       ;; Insert some headers.
2400       (message-generate-headers message-required-news-headers)
2401       ;; Let the user do all of the above.
2402       (run-hooks 'message-header-hook))
2403     (message-cleanup-headers)
2404     (if (not (message-check-news-syntax))
2405         (progn
2406           ;;(message "Posting not performed")
2407           nil)
2408       (unwind-protect
2409           (save-excursion
2410             (set-buffer tembuf)
2411             (buffer-disable-undo (current-buffer))
2412             (erase-buffer)
2413             (insert-buffer message-encoding-buffer)
2414             ;; Remove some headers.
2415             (save-restriction
2416               (message-narrow-to-headers)
2417               ;; Remove some headers.
2418               (message-remove-header message-ignored-news-headers t))
2419             (goto-char (point-max))
2420             ;; require one newline at the end.
2421             (or (= (preceding-char) ?\n)
2422                 (insert ?\n))
2423             (mime-edit-maybe-split-and-send
2424              (function
2425               (lambda ()
2426                 (interactive)
2427                 (save-restriction
2428                   (std11-narrow-to-header mail-header-separator)
2429                   (goto-char (point-min))
2430                   (when (re-search-forward "^Message-Id:" nil t)
2431                     (delete-region (match-end 0)(std11-field-end))
2432                     (insert (concat " " (message-make-message-id)))
2433                     ))
2434                 (funcall message-send-news-function method)
2435                 )))
2436             (setq result (funcall message-send-news-function method)))
2437         (kill-buffer tembuf))
2438       (set-buffer message-edit-buffer)
2439       (if result
2440           (push 'news message-sent-message-via)
2441         (message "Couldn't send message via news: %s"
2442                  (nnheader-get-report (car method)))
2443         nil))))
2444
2445 ;; 1997-09-29 by MORIOKA Tomohiko
2446 (defun message-send-news-with-gnus (method)
2447   (let ((case-fold-search t))
2448     ;; Remove the delimiter.
2449     (goto-char (point-min))
2450     (re-search-forward
2451      (concat "^" (regexp-quote mail-header-separator) "\n"))
2452     (replace-match "\n")
2453     (backward-char 1)
2454     (run-hooks 'message-send-news-hook)
2455     ;;(require (car method))
2456     ;;(funcall (intern (format "%s-open-server" (car method)))
2457     ;;(cadr method) (cddr method))
2458     ;;(setq result
2459     ;;    (funcall (intern (format "%s-request-post" (car method)))
2460     ;;             (cadr method)))
2461     (gnus-open-server method)
2462     (gnus-request-post method)
2463     ))
2464
2465 ;;;
2466 ;;; Header generation & syntax checking.
2467 ;;;
2468
2469 (defmacro message-check (type &rest forms)
2470   "Eval FORMS if TYPE is to be checked."
2471   `(or (message-check-element ,type)
2472        (save-excursion
2473          ,@forms)))
2474
2475 (put 'message-check 'lisp-indent-function 1)
2476 (put 'message-check 'edebug-form-spec '(form body))
2477
2478 (defun message-check-element (type)
2479   "Returns non-nil if this type is not to be checked."
2480   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2481       t
2482     (let ((able (assq type message-syntax-checks)))
2483       (and (consp able)
2484            (eq (cdr able) 'disabled)))))
2485
2486 (defun message-check-news-syntax ()
2487   "Check the syntax of the message."
2488   (save-excursion
2489     (save-restriction
2490       (widen)
2491       (and
2492        ;; We narrow to the headers and check them first.
2493        (save-excursion
2494          (save-restriction
2495            (message-narrow-to-headers)
2496            (message-check-news-header-syntax)))
2497        ;; Check the body.
2498        (save-excursion
2499          (set-buffer message-edit-buffer)
2500          (message-check-news-body-syntax))))))
2501
2502 (defun message-check-news-header-syntax ()
2503   (and
2504    ;; Check the Subject header.
2505    (message-check 'subject
2506      (let* ((case-fold-search t)
2507             (subject (message-fetch-field "subject")))
2508        (or
2509         (and subject
2510              (not (string-match "\\`[ \t]*\\'" subject)))
2511         (ignore
2512          (message
2513           "The subject field is empty or missing.  Posting is denied.")))))
2514    ;; Check for commands in Subject.
2515    (message-check 'subject-cmsg
2516      (if (string-match "^cmsg " (message-fetch-field "subject"))
2517          (y-or-n-p
2518           "The control code \"cmsg\" is in the subject.  Really post? ")
2519        t))
2520    ;; Check for multiple identical headers.
2521    (message-check 'multiple-headers
2522      (let (found)
2523        (while (and (not found)
2524                    (re-search-forward "^[^ \t:]+: " nil t))
2525          (save-excursion
2526            (or (re-search-forward
2527                 (concat "^"
2528                         (regexp-quote
2529                          (setq found
2530                                (buffer-substring
2531                                 (match-beginning 0) (- (match-end 0) 2))))
2532                         ":")
2533                 nil t)
2534                (setq found nil))))
2535        (if found
2536            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2537          t)))
2538    ;; Check for Version and Sendsys.
2539    (message-check 'sendsys
2540      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2541          (y-or-n-p
2542           (format "The article contains a %s command.  Really post? "
2543                   (buffer-substring (match-beginning 0)
2544                                     (1- (match-end 0)))))
2545        t))
2546    ;; See whether we can shorten Followup-To.
2547    (message-check 'shorten-followup-to
2548      (let ((newsgroups (message-fetch-field "newsgroups"))
2549            (followup-to (message-fetch-field "followup-to"))
2550            to)
2551        (when (and newsgroups
2552                   (string-match "," newsgroups)
2553                   (not followup-to)
2554                   (not
2555                    (zerop
2556                     (length
2557                      (setq to (completing-read
2558                                "Followups to: (default all groups) "
2559                                (mapcar (lambda (g) (list g))
2560                                        (cons "poster"
2561                                              (message-tokenize-header
2562                                               newsgroups)))))))))
2563          (goto-char (point-min))
2564          (insert "Followup-To: " to "\n"))
2565        t))
2566    ;; Check "Shoot me".
2567    (message-check 'shoot
2568      (if (re-search-forward
2569           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2570          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2571        t))
2572    ;; Check for Approved.
2573    (message-check 'approved
2574      (if (re-search-forward "^Approved:" nil t)
2575          (y-or-n-p "The article contains an Approved header.  Really post? ")
2576        t))
2577    ;; Check the Message-ID header.
2578    (message-check 'message-id
2579      (let* ((case-fold-search t)
2580             (message-id (message-fetch-field "message-id" t)))
2581        (or (not message-id)
2582            ;; Is there an @ in the ID?
2583            (and (string-match "@" message-id)
2584                 ;; Is there a dot in the ID?
2585                 (string-match "@[^.]*\\." message-id)
2586                 ;; Does the ID end with a dot?
2587                 (not (string-match "\\.>" message-id)))
2588            (y-or-n-p
2589             (format "The Message-ID looks strange: \"%s\".  Really post? "
2590                     message-id)))))
2591    ;; Check the Newsgroups & Followup-To headers.
2592    (message-check 'existing-newsgroups
2593      (let* ((case-fold-search t)
2594             (newsgroups (message-fetch-field "newsgroups"))
2595             (followup-to (message-fetch-field "followup-to"))
2596             (groups (message-tokenize-header
2597                      (if followup-to
2598                          (concat newsgroups "," followup-to)
2599                        newsgroups)))
2600             (hashtb (and (boundp 'gnus-active-hashtb)
2601                          gnus-active-hashtb))
2602             errors)
2603        (if (or (not hashtb)
2604                (not (boundp 'gnus-read-active-file))
2605                (not gnus-read-active-file)
2606                (eq gnus-read-active-file 'some))
2607            t
2608          (while groups
2609            (when (and (not (boundp (intern (car groups) hashtb)))
2610                       (not (equal (car groups) "poster")))
2611              (push (car groups) errors))
2612            (pop groups))
2613          (if (not errors)
2614              t
2615            (y-or-n-p
2616             (format
2617              "Really post to %s unknown group%s: %s "
2618              (if (= (length errors) 1) "this" "these")
2619              (if (= (length errors) 1) "" "s")
2620              (mapconcat 'identity errors ", ")))))))
2621    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2622    (message-check 'valid-newsgroups
2623      (let ((case-fold-search t)
2624            (headers '("Newsgroups" "Followup-To"))
2625            header error)
2626        (while (and headers (not error))
2627          (when (setq header (mail-fetch-field (car headers)))
2628            (if (or
2629                 (not
2630                  (string-match
2631                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2632                   header))
2633                 (memq
2634                  nil (mapcar
2635                       (lambda (g)
2636                         (not (string-match "\\.\\'\\|\\.\\." g)))
2637                       (message-tokenize-header header ","))))
2638                (setq error t)))
2639          (unless error
2640            (pop headers)))
2641        (if (not error)
2642            t
2643          (y-or-n-p
2644           (format "The %s header looks odd: \"%s\".  Really post? "
2645                   (car headers) header)))))
2646    (message-check 'repeated-newsgroups
2647      (let ((case-fold-search t)
2648            (headers '("Newsgroups" "Followup-To"))
2649            header error groups group)
2650        (while (and headers
2651                    (not error))
2652          (when (setq header (mail-fetch-field (pop headers)))
2653            (setq groups (message-tokenize-header header ","))
2654            (while (setq group (pop groups))
2655              (when (member group groups)
2656                (setq error group
2657                      groups nil)))))
2658        (if (not error)
2659            t
2660          (y-or-n-p
2661           (format "Group %s is repeated in headers.  Really post? " error)))))
2662    ;; Check the From header.
2663    (message-check 'from
2664      (let* ((case-fold-search t)
2665             (from (message-fetch-field "from"))
2666             (ad (nth 1 (std11-extract-address-components from))))
2667        (cond
2668         ((not from)
2669          (message "There is no From line.  Posting is denied.")
2670          nil)
2671         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2672              (string-match "\\.\\." ad) ;larsi@ifi..uio
2673              (string-match "@\\." ad)   ;larsi@.ifi.uio
2674              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2675              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2676              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2677          (message
2678           "Denied posting -- the From looks strange: \"%s\"." from)
2679          nil)
2680         (t t))))))
2681
2682 (defun message-check-news-body-syntax ()
2683   (and
2684    ;; Check for long lines.
2685    (message-check 'long-lines
2686      (goto-char (point-min))
2687      (re-search-forward
2688       (concat "^" (regexp-quote mail-header-separator) "$"))
2689      (while (and
2690              (progn
2691                (end-of-line)
2692                (< (current-column) 80))
2693              (zerop (forward-line 1))))
2694      (or (bolp)
2695          (eobp)
2696          (y-or-n-p
2697           "You have lines longer than 79 characters.  Really post? ")))
2698    ;; Check whether the article is empty.
2699    (message-check 'empty
2700      (goto-char (point-min))
2701      (re-search-forward
2702       (concat "^" (regexp-quote mail-header-separator) "$"))
2703      (forward-line 1)
2704      (let ((b (point)))
2705        (goto-char (point-max))
2706        (re-search-backward message-signature-separator nil t)
2707        (beginning-of-line)
2708        (or (re-search-backward "[^ \n\t]" b t)
2709            (y-or-n-p "Empty article.  Really post? "))))
2710    ;; Check for control characters.
2711    (message-check 'control-chars
2712      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2713          (y-or-n-p
2714           "The article contains control characters.  Really post? ")
2715        t))
2716    ;; Check excessive size.
2717    (message-check 'size
2718      (if (> (buffer-size) 60000)
2719          (y-or-n-p
2720           (format "The article is %d octets long.  Really post? "
2721                   (buffer-size)))
2722        t))
2723    ;; Check whether any new text has been added.
2724    (message-check 'new-text
2725      (or
2726       (not message-checksum)
2727       (not (eq (message-checksum) message-checksum))
2728       (y-or-n-p
2729        "It looks like no new text has been added.  Really post? ")))
2730    ;; Check the length of the signature.
2731    (message-check 'signature
2732      (goto-char (point-max))
2733      (if (or (not (re-search-backward message-signature-separator nil t))
2734              (search-forward message-forward-end-separator nil t))
2735          t
2736        (if (> (count-lines (point) (point-max)) 5)
2737            (y-or-n-p
2738             (format
2739              "Your .sig is %d lines; it should be max 4.  Really post? "
2740              (1- (count-lines (point) (point-max)))))
2741          t)))))
2742
2743 (defun message-checksum ()
2744   "Return a \"checksum\" for the current buffer."
2745   (let ((sum 0))
2746     (save-excursion
2747       (goto-char (point-min))
2748       (re-search-forward
2749        (concat "^" (regexp-quote mail-header-separator) "$"))
2750       (while (not (eobp))
2751         (when (not (looking-at "[ \t\n]"))
2752           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2753                             (following-char))))
2754         (forward-char 1)))
2755     sum))
2756
2757 (defun message-do-fcc ()
2758   "Process Fcc headers in the current buffer."
2759   (let ((case-fold-search t)
2760         (coding-system-for-write 'raw-text)
2761         list file)
2762     (save-excursion
2763       (set-buffer (get-buffer-create " *message temp*"))
2764       (buffer-disable-undo (current-buffer))
2765       (erase-buffer)
2766       (insert-buffer-substring message-encoding-buffer)
2767       (save-restriction
2768         (message-narrow-to-headers)
2769         (while (setq file (message-fetch-field "fcc"))
2770           (push file list)
2771           (message-remove-header "fcc" nil t)))
2772       (run-hooks 'message-header-hook 'message-before-do-fcc-hook)
2773       (goto-char (point-min))
2774       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2775       (replace-match "" t t)
2776       ;; Process FCC operations.
2777       (while list
2778         (setq file (pop list))
2779         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2780             ;; Pipe the article to the program in question.
2781             (call-process-region (point-min) (point-max) shell-file-name
2782                                  nil nil nil shell-command-switch
2783                                  (match-string 1 file))
2784           ;; Save the article.
2785           (setq file (expand-file-name file))
2786           (unless (file-exists-p (file-name-directory file))
2787             (make-directory (file-name-directory file) t))
2788           (if (and message-fcc-handler-function
2789                    (not (eq message-fcc-handler-function 'rmail-output)))
2790               (funcall message-fcc-handler-function file)
2791             (if (and (file-readable-p file) (mail-file-babyl-p file))
2792                 (rmail-output file 1 nil t)
2793               (let ((mail-use-rfc822 t))
2794                 (rmail-output file 1 t t))))))
2795
2796       (kill-buffer (current-buffer)))))
2797
2798 (defun message-output (filename)
2799   "Append this article to Unix/babyl mail file.."
2800   (if (and (file-readable-p filename)
2801            (mail-file-babyl-p filename))
2802       (gnus-output-to-rmail filename t)
2803     (gnus-output-to-mail filename t)))
2804
2805 (defun message-cleanup-headers ()
2806   "Do various automatic cleanups of the headers."
2807   ;; Remove empty lines in the header.
2808   (save-restriction
2809     (message-narrow-to-headers)
2810     ;; Remove blank lines.
2811     (while (re-search-forward "^[ \t]*\n" nil t)
2812       (replace-match "" t t))
2813
2814     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2815     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2816     ;; embedded line breaks.
2817     (goto-char (point-min))
2818     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2819       (save-restriction
2820         (narrow-to-region
2821          (point)
2822          (if (re-search-forward "^[^ \t]" nil t)
2823              (match-beginning 0)
2824            (forward-line 1)
2825            (point)))
2826         (goto-char (point-min))
2827         (while (re-search-forward "\n[ \t]+" nil t)
2828           (replace-match " " t t))      ;No line breaks (too confusing)
2829         (goto-char (point-min))
2830         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2831           (replace-match "," t t))
2832         (goto-char (point-min))
2833         ;; Remove trailing commas.
2834         (when (re-search-forward ",+$" nil t)
2835           (replace-match "" t t))))))
2836
2837 (defun message-make-date ()
2838   "Make a valid data header."
2839   (let ((now (current-time)))
2840     (timezone-make-date-arpa-standard
2841      (current-time-string now) (current-time-zone now))))
2842
2843 (defun message-make-followup-subject (subject)
2844   "Make a followup Subject."
2845   (cond
2846    ((and (eq message-use-subject-re 'guess)
2847          (string-match message-subject-encoded-re-regexp subject))
2848     subject)
2849    (message-use-subject-re
2850     (concat "Re: " (message-strip-subject-re subject)))
2851    (t subject)))
2852
2853 (defun message-make-message-id ()
2854   "Make a unique Message-ID."
2855   (concat "<" (message-unique-id)
2856           (let ((psubject (save-excursion (message-fetch-field "subject")))
2857                 (psupersedes
2858                  (save-excursion (message-fetch-field "supersedes"))))
2859             (if (or
2860                  (and message-reply-headers
2861                       (mail-header-references message-reply-headers)
2862                       (mail-header-subject message-reply-headers)
2863                       psubject
2864                       (mail-header-subject message-reply-headers)
2865                       (not (string=
2866                             (message-strip-subject-re
2867                              (mail-header-subject message-reply-headers))
2868                             (message-strip-subject-re psubject))))
2869                  (and psupersedes
2870                       (string-match "_-_@" psupersedes)))
2871                 "_-_" ""))
2872           "@" (message-make-fqdn) ">"))
2873
2874 (defvar message-unique-id-char nil)
2875
2876 ;; If you ever change this function, make sure the new version
2877 ;; cannot generate IDs that the old version could.
2878 ;; You might for example insert a "." somewhere (not next to another dot
2879 ;; or string boundary), or modify the "fsf" string.
2880 (defun message-unique-id ()
2881   ;; Don't use microseconds from (current-time), they may be unsupported.
2882   ;; Instead we use this randomly inited counter.
2883   (setq message-unique-id-char
2884         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2885            ;; (current-time) returns 16-bit ints,
2886            ;; and 2^16*25 just fits into 4 digits i base 36.
2887            (* 25 25)))
2888   (let ((tm (current-time)))
2889     (concat
2890      (if (memq system-type '(ms-dos emx vax-vms))
2891          (let ((user (downcase (user-login-name))))
2892            (while (string-match "[^a-z0-9_]" user)
2893              (aset user (match-beginning 0) ?_))
2894            user)
2895        (message-number-base36 (user-uid) -1))
2896      (message-number-base36 (+ (car   tm)
2897                                (lsh (% message-unique-id-char 25) 16)) 4)
2898      (message-number-base36 (+ (nth 1 tm)
2899                                (lsh (/ message-unique-id-char 25) 16)) 4)
2900      ;; Append the newsreader name, because while the generated
2901      ;; ID is unique to this newsreader, other newsreaders might
2902      ;; otherwise generate the same ID via another algorithm.
2903      ".fsf")))
2904
2905 (defun message-number-base36 (num len)
2906   (if (if (< len 0)
2907           (<= num 0)
2908         (= len 0))
2909       ""
2910     (concat (message-number-base36 (/ num 36) (1- len))
2911             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2912                                   (% num 36))))))
2913
2914 (defun message-make-organization ()
2915   "Make an Organization header."
2916   (let* ((organization
2917           (when message-user-organization
2918                 (if (message-functionp message-user-organization)
2919                     (funcall message-user-organization)
2920                   message-user-organization))))
2921     (save-excursion
2922       (message-set-work-buffer)
2923       (cond ((stringp organization)
2924              (insert organization))
2925             ((and (eq t organization)
2926                   message-user-organization-file
2927                   (file-exists-p message-user-organization-file))
2928              (insert-file-contents message-user-organization-file)))
2929       (goto-char (point-min))
2930       (while (re-search-forward "[\t\n]+" nil t)
2931         (replace-match "" t t))
2932       (unless (zerop (buffer-size))
2933         (buffer-string)))))
2934
2935 (defun message-make-lines ()
2936   "Count the number of lines and return numeric string."
2937   (save-excursion
2938     (save-restriction
2939       (widen)
2940       (goto-char (point-min))
2941       (re-search-forward
2942        (concat "^" (regexp-quote mail-header-separator) "$"))
2943       (forward-line 1)
2944       (int-to-string (count-lines (point) (point-max))))))
2945
2946 (defun message-make-in-reply-to ()
2947   "Return the In-Reply-To header for this message."
2948   (when message-reply-headers
2949     (let ((mid (mail-header-message-id message-reply-headers))
2950           (from (mail-header-from message-reply-headers))
2951           (date (mail-header-date message-reply-headers)))
2952       (when mid
2953         (concat mid
2954                 (when from
2955                   (let ((pair (std11-extract-address-components from)))
2956                     (concat "\n ("
2957                             (or (car pair) (cadr pair))
2958                             "'s message of " 
2959                             (if (or (not date) (string= date ""))
2960                                 "(unknown date)" date)
2961                             ")"))))))))
2962
2963 (defun message-make-distribution ()
2964   "Make a Distribution header."
2965   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2966     (cond ((message-functionp message-distribution-function)
2967            (funcall message-distribution-function))
2968           (t orig-distribution))))
2969
2970 (defun message-make-expires ()
2971   "Return an Expires header based on `message-expires'."
2972   (let ((current (current-time))
2973         (future (* 1.0 message-expires 60 60 24)))
2974     ;; Add the future to current.
2975     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2976     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2977     ;; Return the date in the future in UT.
2978     (timezone-make-date-arpa-standard
2979      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2980
2981 (defun message-make-path ()
2982   "Return uucp path."
2983   (let ((login-name (user-login-name)))
2984     (cond ((null message-user-path)
2985            (concat (system-name) "!" login-name))
2986           ((stringp message-user-path)
2987            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2988            (concat message-user-path "!" login-name))
2989           (t login-name))))
2990
2991 (defun message-make-from ()
2992   "Make a From header."
2993   (let* ((style message-from-style)
2994          (login (message-make-address))
2995          (fullname
2996           (or (and (boundp 'user-full-name)
2997                    user-full-name)
2998               (user-full-name))))
2999     (when (string= fullname "&")
3000       (setq fullname (user-login-name)))
3001     (save-excursion
3002       (message-set-work-buffer)
3003       (cond
3004        ((or (null style)
3005             (equal fullname ""))
3006         (insert login))
3007        ((or (eq style 'angles)
3008             (and (not (eq style 'parens))
3009                  ;; Use angles if no quoting is needed, or if parens would
3010                  ;; need quoting too.
3011                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3012                      (let ((tmp (concat fullname nil)))
3013                        (while (string-match "([^()]*)" tmp)
3014                          (aset tmp (match-beginning 0) ?-)
3015                          (aset tmp (1- (match-end 0)) ?-))
3016                        (string-match "[\\()]" tmp)))))
3017         (insert fullname)
3018         (goto-char (point-min))
3019         ;; Look for a character that cannot appear unquoted
3020         ;; according to RFC 822.
3021         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3022           ;; Quote fullname, escaping specials.
3023           (goto-char (point-min))
3024           (insert "\"")
3025           (while (re-search-forward "[\"\\]" nil 1)
3026             (replace-match "\\\\\\&" t))
3027           (insert "\""))
3028         (insert " <" login ">"))
3029        (t                               ; 'parens or default
3030         (insert login " (")
3031         (let ((fullname-start (point)))
3032           (insert fullname)
3033           (goto-char fullname-start)
3034           ;; RFC 822 says \ and nonmatching parentheses
3035           ;; must be escaped in comments.
3036           ;; Escape every instance of ()\ ...
3037           (while (re-search-forward "[()\\]" nil 1)
3038             (replace-match "\\\\\\&" t))
3039           ;; ... then undo escaping of matching parentheses,
3040           ;; including matching nested parentheses.
3041           (goto-char fullname-start)
3042           (while (re-search-forward
3043                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3044                   nil 1)
3045             (replace-match "\\1(\\3)" t)
3046             (goto-char fullname-start)))
3047         (insert ")")))
3048       (buffer-string))))
3049
3050 (defun message-make-sender ()
3051   "Return the \"real\" user address.
3052 This function tries to ignore all user modifications, and
3053 give as trustworthy answer as possible."
3054   (concat (user-login-name) "@" (system-name)))
3055
3056 (defun message-make-address ()
3057   "Make the address of the user."
3058   (or (message-user-mail-address)
3059       (concat (user-login-name) "@" (message-make-domain))))
3060
3061 (defun message-user-mail-address ()
3062   "Return the pertinent part of `user-mail-address'."
3063   (when user-mail-address
3064     (if (string-match " " user-mail-address)
3065         (nth 1 (std11-extract-address-components user-mail-address))
3066       user-mail-address)))
3067
3068 (defun message-make-fqdn ()
3069   "Return user's fully qualified domain name."
3070   (let ((system-name (system-name))
3071         (user-mail (message-user-mail-address)))
3072     (cond
3073      ((string-match "[^.]\\.[^.]" system-name)
3074       ;; `system-name' returned the right result.
3075       system-name)
3076      ;; Try `mail-host-address'.
3077      ((and (boundp 'mail-host-address)
3078            (stringp mail-host-address)
3079            (string-match "\\." mail-host-address))
3080       mail-host-address)
3081      ;; We try `user-mail-address' as a backup.
3082      ((and user-mail
3083            (string-match "\\." user-mail)
3084            (string-match "@\\(.*\\)\\'" user-mail))
3085       (match-string 1 user-mail))
3086      ;; Default to this bogus thing.
3087      (t
3088       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3089
3090 (defun message-make-host-name ()
3091   "Return the name of the host."
3092   (let ((fqdn (message-make-fqdn)))
3093     (string-match "^[^.]+\\." fqdn)
3094     (substring fqdn 0 (1- (match-end 0)))))
3095
3096 (defun message-make-domain ()
3097   "Return the domain name."
3098   (or mail-host-address
3099       (message-make-fqdn)))
3100
3101 ;; Dummy to avoid byte-compile warning.
3102 (defvar mule-version)
3103 (defvar emacs-beta-version)
3104 (defvar xemacs-codename)
3105
3106 (defun message-make-user-agent ()
3107   "Return user-agent info."
3108   (let ((user-agent
3109          (concat
3110           ;; SEMI: '("SEMI" "CODENAME" V1 V2 V3)
3111           (format "%s/%s (%s)"
3112                   (nth 0 mime-user-interface-version)
3113                   (mapconcat #'number-to-string
3114                              (cdr (cdr mime-user-interface-version))
3115                              ".")
3116                   (nth 1 mime-user-interface-version))
3117           ;; FLIM: "FLIM VERSION - \"CODENAME\"[...]"
3118           (if (string-match
3119                "\\`\\([^ ]+\\) \\([^ ]+\\) - \"\\([^\"]+\\)\"\\(.*\\)\\'"
3120                mime-library-version-string)
3121               (format " %s/%s (%s%s)"
3122                       (match-string 1 mime-library-version-string)
3123                       (match-string 2 mime-library-version-string)
3124                       (match-string 3 mime-library-version-string)
3125                       (match-string 4 mime-library-version-string))
3126             " FLIM")
3127           "\n "
3128           ;; EMACS/VERSION
3129           (if (featurep 'xemacs)
3130               ;; XEmacs
3131               (concat
3132                (format "XEmacs/%d.%d" emacs-major-version emacs-minor-version)
3133                (if (and (boundp 'emacs-beta-version) emacs-beta-version)
3134                    (format "beta%d" emacs-beta-version)
3135                  "")
3136                (if (and (boundp 'xemacs-codename) xemacs-codename)
3137                    (concat " (" xemacs-codename ")")
3138                  "")
3139                )
3140             ;; not XEmacs
3141             (concat
3142              (format "Emacs/%d.%d" emacs-major-version emacs-minor-version)
3143              (if (>= emacs-major-version 20)
3144                  (if (and (boundp 'enable-multibyte-characters)
3145                           enable-multibyte-characters)
3146                      ""                 ; Should return " (multibyte)"?
3147                    " (unibyte)"))
3148              ))
3149           ;; MULE[/VERSION]
3150           (if (featurep 'mule)
3151               (if (and (boundp 'mule-version) mule-version)
3152                   (concat " MULE/" mule-version)
3153                 " MULE")                ; no mule-version
3154             "")                         ; not Mule
3155           ;; Meadow/VERSION
3156           (if (featurep 'meadow)
3157               (let ((version (Meadow-version)))
3158                 (if (string-match "\\`Meadow.\\([^ ]*\\)\\( (.*)\\)\\'" version)
3159                     (concat " Meadow/"
3160                             (match-string 1 version)
3161                             (match-string 2 version)
3162                             )
3163                   "Meadow"))            ; unknown format
3164             "")                         ; not Meadow
3165           )))
3166     (if message-user-agent
3167         (concat message-user-agent " " user-agent)
3168       user-agent)))
3169
3170 (defun message-generate-headers (headers)
3171   "Prepare article HEADERS.
3172 Headers already prepared in the buffer are not modified."
3173   (save-restriction
3174     (message-narrow-to-headers)
3175     (let* ((Date (message-make-date))
3176            (Message-ID (message-make-message-id))
3177            (Organization (message-make-organization))
3178            (From (message-make-from))
3179            (Path (message-make-path))
3180            (Subject nil)
3181            (Newsgroups nil)
3182            (In-Reply-To (message-make-in-reply-to))
3183            (To nil)
3184            (Distribution (message-make-distribution))
3185            (Lines (message-make-lines))
3186            (User-Agent (message-make-user-agent))
3187            (Expires (message-make-expires))
3188            (case-fold-search t)
3189            header value elem)
3190       ;; First we remove any old generated headers.
3191       (let ((headers message-deletable-headers))
3192         (unless (buffer-modified-p)
3193           (setq headers (delq 'Message-ID (copy-sequence headers))))
3194         (while headers
3195           (goto-char (point-min))
3196           (and (re-search-forward
3197                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3198                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3199                (message-delete-line))
3200           (pop headers)))
3201       ;; Go through all the required headers and see if they are in the
3202       ;; articles already.  If they are not, or are empty, they are
3203       ;; inserted automatically - except for Subject, Newsgroups and
3204       ;; Distribution.
3205       (while headers
3206         (goto-char (point-min))
3207         (setq elem (pop headers))
3208         (if (consp elem)
3209             (if (eq (car elem) 'optional)
3210                 (setq header (cdr elem))
3211               (setq header (car elem)))
3212           (setq header elem))
3213         (when (or (not (re-search-forward
3214                         (concat "^"
3215                                 (regexp-quote
3216                                  (downcase
3217                                   (if (stringp header)
3218                                       header
3219                                     (symbol-name header))))
3220                                 ":")
3221                         nil t))
3222                   (progn
3223                     ;; The header was found.  We insert a space after the
3224                     ;; colon, if there is none.
3225                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
3226                     ;; Find out whether the header is empty...
3227                     (looking-at "[ \t]*$")))
3228           ;; So we find out what value we should insert.
3229           (setq value
3230                 (cond
3231                  ((and (consp elem) (eq (car elem) 'optional))
3232                   ;; This is an optional header.  If the cdr of this
3233                   ;; is something that is nil, then we do not insert
3234                   ;; this header.
3235                   (setq header (cdr elem))
3236                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3237                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3238                  ((consp elem)
3239                   ;; The element is a cons.  Either the cdr is a
3240                   ;; string to be inserted verbatim, or it is a
3241                   ;; function, and we insert the value returned from
3242                   ;; this function.
3243                   (or (and (stringp (cdr elem)) (cdr elem))
3244                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3245                  ((and (boundp header) (symbol-value header))
3246                   ;; The element is a symbol.  We insert the value
3247                   ;; of this symbol, if any.
3248                   (symbol-value header))
3249                  (t
3250                   ;; We couldn't generate a value for this header,
3251                   ;; so we just ask the user.
3252                   (read-from-minibuffer
3253                    (format "Empty header for %s; enter value: " header)))))
3254           ;; Finally insert the header.
3255           (when (and value
3256                      (not (equal value "")))
3257             (save-excursion
3258               (if (bolp)
3259                   (progn
3260                     ;; This header didn't exist, so we insert it.
3261                     (goto-char (point-max))
3262                     (insert (if (stringp header) header (symbol-name header))
3263                             ": " value "\n")
3264                     (forward-line -1))
3265                 ;; The value of this header was empty, so we clear
3266                 ;; totally and insert the new value.
3267                 (delete-region (point) (gnus-point-at-eol))
3268                 (insert value))
3269               ;; Add the deletable property to the headers that require it.
3270               (and (memq header message-deletable-headers)
3271                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3272                    (add-text-properties
3273                     (point) (match-end 0)
3274                     '(message-deletable t face italic) (current-buffer)))))))
3275       ;; Insert new Sender if the From is strange.
3276       (let ((from (message-fetch-field "from"))
3277             (sender (message-fetch-field "sender"))
3278             (secure-sender (message-make-sender)))
3279         (when (and from
3280                    (not (message-check-element 'sender))
3281                    (not (string=
3282                          (downcase
3283                           (cadr (std11-extract-address-components from)))
3284                          (downcase secure-sender)))
3285                    (or (null sender)
3286                        (not
3287                         (string=
3288                          (downcase
3289                           (cadr (std11-extract-address-components sender)))
3290                          (downcase secure-sender)))))
3291           (goto-char (point-min))
3292           ;; Rename any old Sender headers to Original-Sender.
3293           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3294             (beginning-of-line)
3295             (insert "Original-")
3296             (beginning-of-line))
3297           (when (or (message-news-p)
3298                     (string-match "@.+\\.." secure-sender))
3299             (insert "Sender: " secure-sender "\n")))))))
3300
3301 (defun message-insert-courtesy-copy ()
3302   "Insert a courtesy message in mail copies of combined messages."
3303   (let (newsgroups)
3304     (save-excursion
3305       (save-restriction
3306         (message-narrow-to-headers)
3307         (when (setq newsgroups (message-fetch-field "newsgroups"))
3308           (goto-char (point-max))
3309           (insert "Posted-To: " newsgroups "\n")))
3310       (forward-line 1)
3311       (when message-courtesy-message
3312         (cond
3313          ((string-match "%s" message-courtesy-message)
3314           (insert (format message-courtesy-message newsgroups)))
3315          (t
3316           (insert message-courtesy-message)))))))
3317
3318 ;;;
3319 ;;; Setting up a message buffer
3320 ;;;
3321
3322 (defun message-fill-address (header value)
3323   (save-restriction
3324     (narrow-to-region (point) (point))
3325     (insert (capitalize (symbol-name header))
3326             ": "
3327             (if (consp value) (car value) value)
3328             "\n")
3329     (narrow-to-region (point-min) (1- (point-max)))
3330     (let (quoted last)
3331       (goto-char (point-min))
3332       (while (not (eobp))
3333         (skip-chars-forward "^,\"" (point-max))
3334         (if (or (= (following-char) ?,)
3335                 (eobp))
3336             (when (not quoted)
3337               (if last
3338                   (save-excursion
3339                     (goto-char last)
3340                     (looking-at "[ \t]*")
3341                     (replace-match "\n " t t)))
3342               (setq last (1+ (point))))
3343           (setq quoted (not quoted)))
3344         (unless (eobp)
3345           (forward-char 1))))
3346     (goto-char (point-max))
3347     (widen)
3348     (forward-line 1)))
3349
3350 (defun message-fill-references (header value)
3351   (insert (capitalize (symbol-name header))
3352           ": "
3353           (std11-fill-msg-id-list-string
3354           (if (consp value) (car value) value))
3355           "\n"))
3356
3357 (defun message-fill-header (header value)
3358   (let ((begin (point))
3359         (fill-column 78)
3360         (fill-prefix " "))
3361     (insert (capitalize (symbol-name header))
3362             ": "
3363             (if (consp value) (car value) value)
3364             "\n")
3365     (save-restriction
3366       (narrow-to-region begin (point))
3367       (fill-region-as-paragraph begin (point))
3368       ;; Tapdance around looong Message-IDs.
3369       (forward-line -1)
3370       (when (looking-at "[ \t]*$")
3371         (message-delete-line))
3372       (goto-char begin)
3373       (re-search-forward ":" nil t)
3374       (when (looking-at "\n[ \t]+")
3375         (replace-match " " t t))
3376       (goto-char (point-max)))))
3377
3378 (defun message-shorten-references (header references)
3379   "Limit REFERENCES to be shorter than 988 characters."
3380   (let ((max 988)
3381         (cut 4)
3382         refs)
3383     (with-temp-buffer
3384       (insert references)
3385       (goto-char (point-min))
3386       (while (re-search-forward "<[^>]+>" nil t)
3387         (push (match-string 0) refs))
3388       (setq refs (nreverse refs))
3389       (while (> (length (mapconcat 'identity refs " ")) max)
3390         (when (< (length refs) (1+ cut))
3391           (decf cut))
3392         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3393     (insert (capitalize (symbol-name header)) ": "
3394             (mapconcat 'identity refs " ") "\n")))
3395
3396 (defun message-position-point ()
3397   "Move point to where the user probably wants to find it."
3398   (message-narrow-to-headers)
3399   (cond
3400    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3401     (search-backward ":" )
3402     (widen)
3403     (forward-char 1)
3404     (if (= (following-char) ? )
3405         (forward-char 1)
3406       (insert " ")))
3407    (t
3408     (goto-char (point-max))
3409     (widen)
3410     (forward-line 1)
3411     (unless (looking-at "$")
3412       (forward-line 2)))
3413    (sit-for 0)))
3414
3415 (defun message-buffer-name (type &optional to group)
3416   "Return a new (unique) buffer name based on TYPE and TO."
3417   (cond
3418    ;; Check whether `message-generate-new-buffers' is a function,
3419    ;; and if so, call it.
3420    ((message-functionp message-generate-new-buffers)
3421     (funcall message-generate-new-buffers type to group))
3422    ;; Generate a new buffer name The Message Way.
3423    (message-generate-new-buffers
3424     (generate-new-buffer-name
3425      (concat "*" type
3426              (if to
3427                  (concat " to "
3428                          (or (car (std11-extract-address-components to))
3429                              to) "")
3430                "")
3431              (if (and group (not (string= group ""))) (concat " on " group) "")
3432              "*")))
3433    ;; Use standard name.
3434    (t
3435     (format "*%s message*" type))))
3436
3437 (defun message-pop-to-buffer (name)
3438   "Pop to buffer NAME, and warn if it already exists and is modified."
3439   (let ((pop-up-frames pop-up-frames)
3440         (special-display-buffer-names special-display-buffer-names)
3441         (special-display-regexps special-display-regexps)
3442         (same-window-buffer-names same-window-buffer-names)
3443         (same-window-regexps same-window-regexps)
3444         (buffer (get-buffer name))
3445         (cur (current-buffer)))
3446     (if (or (and (featurep 'xemacs)
3447                  (not (eq 'tty (device-type))))
3448             window-system
3449             (>= emacs-major-version 20))
3450         (when message-use-multi-frames
3451           (setq pop-up-frames t
3452                 special-display-buffer-names nil
3453                 special-display-regexps nil
3454                 same-window-buffer-names nil
3455                 same-window-regexps nil))
3456       (setq pop-up-frames nil))
3457     (if (and buffer
3458              (buffer-name buffer))
3459         (progn
3460           (set-buffer (pop-to-buffer buffer))
3461           (when (and (buffer-modified-p)
3462                      (not (y-or-n-p
3463                            "Message already being composed; erase? ")))
3464             (error "Message being composed")))
3465       (set-buffer (pop-to-buffer name)))
3466     (erase-buffer)
3467     (message-mode)
3468     (when pop-up-frames
3469       (make-local-variable 'message-original-frame)
3470       (setq message-original-frame (selected-frame)))))
3471
3472 (defun message-do-send-housekeeping ()
3473   "Kill old message buffers."
3474   ;; We might have sent this buffer already.  Delete it from the
3475   ;; list of buffers.
3476   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3477   (while (and message-max-buffers
3478               message-buffer-list
3479               (>= (length message-buffer-list) message-max-buffers))
3480     ;; Kill the oldest buffer -- unless it has been changed.
3481     (let ((buffer (pop message-buffer-list)))
3482       (when (and (buffer-name buffer)
3483                  (not (buffer-modified-p buffer)))
3484         (kill-buffer buffer))))
3485   ;; Rename the buffer.
3486   (if message-send-rename-function
3487       (funcall message-send-rename-function)
3488     (when (string-match "\\`\\*" (buffer-name))
3489       (rename-buffer
3490        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3491   ;; Push the current buffer onto the list.
3492   (when message-max-buffers
3493     (setq message-buffer-list
3494           (nconc message-buffer-list (list (current-buffer))))))
3495
3496 (defvar mc-modes-alist)
3497 (defun message-setup (headers &optional replybuffer actions)
3498   (when (and (boundp 'mc-modes-alist)
3499              (not (assq 'message-mode mc-modes-alist)))
3500     (push '(message-mode (encrypt . mc-encrypt-message)
3501                          (sign . mc-sign-message))
3502           mc-modes-alist))
3503   (when actions
3504     (setq message-send-actions actions))
3505   (setq message-reply-buffer replybuffer)
3506   (goto-char (point-min))
3507   ;; Insert all the headers.
3508   (mail-header-format
3509    (let ((h headers)
3510          (alist message-header-format-alist))
3511      (while h
3512        (unless (assq (caar h) message-header-format-alist)
3513          (push (list (caar h)) alist))
3514        (pop h))
3515      alist)
3516    headers)
3517   (delete-region (point) (progn (forward-line -1) (point)))
3518   (when message-default-headers
3519     (insert message-default-headers)
3520     (or (bolp) (insert ?\n)))
3521   (put-text-property
3522    (point)
3523    (progn
3524      (insert mail-header-separator "\n")
3525      (1- (point)))
3526    'read-only nil)
3527   (forward-line -1)
3528   (when (message-news-p)
3529     (when message-default-news-headers
3530       (insert message-default-news-headers)
3531       (or (bolp) (insert ?\n)))
3532     (when message-generate-headers-first
3533       (message-generate-headers
3534        (delq 'Lines
3535              (delq 'Subject
3536                    (copy-sequence message-required-news-headers))))))
3537   (when (message-mail-p)
3538     (when message-default-mail-headers
3539       (insert message-default-mail-headers)
3540       (or (bolp) (insert ?\n)))
3541     (when message-generate-headers-first
3542       (message-generate-headers
3543        (delq 'Lines
3544              (delq 'Subject
3545                    (copy-sequence message-required-mail-headers))))))
3546   (run-hooks 'message-signature-setup-hook)
3547   (message-insert-signature)
3548   (save-restriction
3549     (message-narrow-to-headers)
3550     (run-hooks 'message-header-setup-hook))
3551   (set-buffer-modified-p nil)
3552   (setq buffer-undo-list nil)
3553   (run-hooks 'message-setup-hook)
3554   (message-position-point)
3555   (undo-boundary))
3556
3557 (defun message-set-auto-save-file-name ()
3558   "Associate the message buffer with a file in the drafts directory."
3559   (when message-autosave-directory
3560     (if (gnus-alive-p)
3561         (setq message-draft-article
3562               (nndraft-request-associate-buffer "drafts"))
3563       (setq buffer-file-name (expand-file-name "*message*"
3564                                                message-autosave-directory))
3565       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3566     (clear-visited-file-modtime)))
3567
3568 (defun message-disassociate-draft ()
3569   "Disassociate the message buffer from the drafts directory."
3570   (when message-draft-article
3571     (nndraft-request-expire-articles
3572      (list message-draft-article) "drafts" nil t)))
3573
3574 \f
3575
3576 ;;;
3577 ;;; Commands for interfacing with message
3578 ;;;
3579
3580 ;;;###autoload
3581 (defun message-mail (&optional to subject
3582                                other-headers continue switch-function
3583                                yank-action send-actions)
3584   "Start editing a mail message to be sent.
3585 OTHER-HEADERS is an alist of header/value pairs."
3586   (interactive)
3587   (let ((message-this-is-mail t))
3588     (message-pop-to-buffer (message-buffer-name "mail" to))
3589     (message-setup
3590      (nconc
3591       `((To . ,(or to "")) (Subject . ,(or subject "")))
3592       (when other-headers other-headers)))))
3593
3594 ;;;###autoload
3595 (defun message-news (&optional newsgroups subject)
3596   "Start editing a news article to be sent."
3597   (interactive)
3598   (let ((message-this-is-news t))
3599     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3600     (message-setup `((Newsgroups . ,(or newsgroups ""))
3601                      (Subject . ,(or subject ""))))))
3602
3603 ;;;###autoload
3604 (defun message-reply (&optional to-address wide)
3605   "Start editing a reply to the article in the current buffer."
3606   (interactive)
3607   (let ((cur (current-buffer))
3608         (inhibit-point-motion-hooks t)
3609         from date subject mct mft mrt
3610         never-mct to cc
3611         references message-id follow-to gnus-warning)
3612     (save-restriction
3613       (message-narrow-to-head)
3614       ;; Allow customizations to have their say.
3615       (if (not wide)
3616           ;; This is a regular reply.
3617           (if (message-functionp message-reply-to-function)
3618               (setq follow-to (funcall message-reply-to-function)))
3619         ;; This is a followup.
3620         (if (message-functionp message-wide-reply-to-function)
3621             (save-excursion
3622               (setq follow-to
3623                     (funcall message-wide-reply-to-function)))))
3624       ;; Find all relevant headers we need.
3625       (setq from (message-fetch-field "from")
3626             date (message-fetch-field "date" t)
3627             subject (or (message-fetch-field "subject") "none")
3628             references (message-fetch-field "references")
3629             message-id (message-fetch-field "message-id" t)
3630             to (message-fetch-field "to")
3631             cc (message-fetch-field "cc")
3632             mct (when (and wide message-use-mail-copies-to)
3633                   (message-fetch-field "mail-copies-to"))
3634             mft (when (and wide message-use-mail-followup-to)
3635                   (message-fetch-field "mail-followup-to"))
3636             mrt (when message-use-mail-reply-to
3637                   (or (message-fetch-field "mail-reply-to")
3638                       (message-fetch-field "reply-to")))
3639             gnus-warning (message-fetch-field "gnus-warning"))
3640       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
3641         (setq message-id (match-string 0 gnus-warning)))
3642       ;; Remove any (buggy) Re:'s that are present and make a
3643       ;; proper one.
3644       (setq subject (message-make-followup-subject subject))
3645       (widen))
3646
3647     ;; Handle special values of Mail-Copies-To.
3648     (when mct
3649       (cond
3650        ((and (equal (downcase mct) "never")
3651              (or (not (eq message-use-mail-copies-to 'ask))
3652                  (message-y-or-n-p
3653                   (concat "Obey Mail-Copies-To: never? ") t "\
3654 You should normally obey the Mail-Copies-To: header.
3655
3656         `Mail-Copies-To: never'
3657 directs you not to send your response to the author.")))
3658         (setq never-mct t)
3659         (setq mct nil))
3660        ((and (equal (downcase mct) "always")
3661              (or (not (eq message-use-mail-copies-to 'ask))
3662                  (message-y-or-n-p
3663                   (concat "Obey Mail-Copies-To: always? ") t "\
3664 You should normally obey the Mail-Copies-To: header.
3665
3666         `Mail-Copies-To: always'
3667 sends a copy of your response to the author.")))
3668         (setq mct (or mrt from)))
3669        ((and (eq message-use-mail-copies-to 'ask)
3670              (not 
3671               (message-y-or-n-p
3672                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
3673 You should normally obey the Mail-Copies-To: header.
3674
3675         `Mail-Copies-To: " mct "'
3676 sends a copy of your response to " (if (string-match "," mct)
3677                                        "the specified addresses"
3678                                      "that address") ".")))
3679         (setq mct nil))
3680        ))
3681
3682     (unless follow-to
3683       (cond
3684        (to-address (setq follow-to (list (cons 'To to-address))))
3685        ((not wide) (setq follow-to (list (cons 'To (or mrt from)))))
3686        ;; Handle Mail-Followup-To.
3687        ((and mft
3688              (or (not (eq message-use-mail-followup-to 'ask))
3689                  (message-y-or-n-p
3690                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
3691 You should normally obey the Mail-Followup-To: header.
3692
3693         `Mail-Followup-To: " mft "'
3694 directs your response to " (if (string-match "," mft)
3695                                "the specified addresses"
3696                              "that address only") ".
3697
3698 A typical situation where Mail-Followup-To is used is when the author thinks
3699 that further discussion should take place only in "
3700                   (if (string-match "," mft)
3701                       "the specified mailing lists"
3702                     "that mailing list") ".")))
3703         (setq follow-to (list (cons 'To mft)))
3704         (when mct
3705           (push (cons 'Cc mct) follow-to)))
3706        (t
3707         (let (ccalist)
3708           (save-excursion
3709             (message-set-work-buffer)
3710             (unless never-mct
3711               (insert (or mrt from "")))
3712             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3713             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3714             (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3715             (goto-char (point-min))
3716             (while (re-search-forward "[ \t]+" nil t)
3717               (replace-match " " t t))
3718             ;; Remove addresses that match `rmail-dont-reply-to-names'.
3719             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3720                       (erase-buffer)))
3721             (goto-char (point-min))
3722             ;; Perhaps Mail-Copies-To: never removed the only address?
3723             (when (eobp)
3724               (insert (or mrt from "")))
3725             (setq ccalist
3726                   (mapcar
3727                    (lambda (addr)
3728                      (cons (mail-strip-quoted-names addr) addr))
3729                    (message-tokenize-header (buffer-string))))
3730             (let ((s ccalist))
3731               (while s
3732                 (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3733           (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3734           (when ccalist
3735             (let ((ccs (cons 'Cc (mapconcat
3736                                   (lambda (addr) (cdr addr)) ccalist ", "))))
3737               (when (string-match "^ +" (cdr ccs))
3738                 (setcdr ccs (substring (cdr ccs) (match-end 0))))
3739               (push ccs follow-to)))))))
3740
3741     (message-pop-to-buffer (message-buffer-name
3742                             (if wide "wide reply" "reply") from
3743                             (if wide to-address nil)))
3744
3745     (setq message-reply-headers
3746           (vector 0 subject from date message-id references 0 0 ""))
3747
3748     (message-setup
3749      `((Subject . ,subject)
3750        ,@follow-to
3751        ,@(if (or references message-id)
3752              `((References . ,(concat (or references "") (and references " ")
3753                                       (or message-id ""))))))
3754      cur)))
3755
3756 ;;;###autoload
3757 (defun message-wide-reply (&optional to-address)
3758   "Make a \"wide\" reply to the message in the current buffer."
3759   (interactive)
3760   (message-reply to-address t))
3761
3762 ;;;###autoload
3763 (defun message-followup (&optional to-newsgroups)
3764   "Follow up to the message in the current buffer."
3765   (interactive)
3766   (let ((cur (current-buffer))
3767         (inhibit-point-motion-hooks t)
3768         from date subject mct mft mrt
3769         (message-this-is-news t)
3770         followup-to distribution newsgroups posted-to
3771         references message-id follow-to gnus-warning)
3772     (save-restriction
3773       (message-narrow-to-head)
3774       ;; Allow customizations to have their say.
3775       ;; This is a followup.
3776       (when (message-functionp message-followup-to-function)
3777         (setq follow-to
3778               (funcall message-followup-to-function)))
3779       ;; Find all relevant headers we need.
3780       (setq from (message-fetch-field "from")
3781             date (message-fetch-field "date" t)
3782             subject (or (message-fetch-field "subject") "none")
3783             references (message-fetch-field "references")
3784             message-id (message-fetch-field "message-id" t)
3785             followup-to (when message-use-followup-to
3786                           (message-fetch-field "followup-to"))
3787             distribution (message-fetch-field "distribution")
3788             newsgroups (message-fetch-field "newsgroups")
3789             posted-to (message-fetch-field "posted-to")
3790             mct (when message-use-mail-copies-to
3791                   (message-fetch-field "mail-copies-to"))
3792             mft (when message-use-mail-followup-to
3793                   (message-fetch-field "mail-followup-to"))
3794             mrt (when message-use-mail-reply-to
3795                   (or (message-fetch-field "mail-reply-to")
3796                       (message-fetch-field "reply-to")))
3797             gnus-warning (message-fetch-field "gnus-warning"))
3798       (when (and gnus-warning (string-match "<[^>]+>" gnus-warning))
3799         (setq message-id (match-string 0 gnus-warning)))
3800       ;; Remove bogus distribution.
3801       (when (and (stringp distribution)
3802                  (let ((case-fold-search t))
3803                    (string-match "world" distribution)))
3804         (setq distribution nil))
3805       ;; Remove any (buggy) Re:'s that are present and make a
3806       ;; proper one.
3807       (setq subject (message-make-followup-subject subject))
3808       (widen))
3809
3810     ;; Handle special values of Mail-Copies-To.
3811     (when mct
3812       (cond
3813        ((and (equal (downcase mct) "never")
3814              (or (not (eq message-use-mail-copies-to 'ask))
3815                  (message-y-or-n-p
3816                   (concat "Obey Mail-Copies-To: never? ") t "\
3817 You should normally obey the Mail-Copies-To: header.
3818
3819         `Mail-Copies-To: never'
3820 directs you not to send your response to the author.")))
3821         (setq mct nil))
3822        ((and (equal (downcase mct) "always")
3823              (or (not (eq message-use-mail-copies-to 'ask))
3824                  (message-y-or-n-p
3825                   (concat "Obey Mail-Copies-To: always? ") t "\
3826 You should normally obey the Mail-Copies-To: header.
3827
3828         `Mail-Copies-To: always'
3829 sends a copy of your response to the author.")))
3830         (setq mct (or mrt from)))
3831        ((and (eq message-use-mail-copies-to 'ask)
3832              (not 
3833               (message-y-or-n-p
3834                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
3835 You should normally obey the Mail-Copies-To: header.
3836
3837         `Mail-Copies-To: " mct "'
3838 sends a copy of your response to " (if (string-match "," mct)
3839                                        "the specified addresses"
3840                                      "that address") ".")))
3841         (setq mct nil))
3842        ))
3843
3844     (unless follow-to
3845       (cond
3846        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
3847        ;; Handle Followup-To.
3848        (followup-to
3849         (cond
3850          ((equal (downcase followup-to) "poster")
3851           (if (or (eq message-use-followup-to 'use)
3852                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
3853 You should normally obey the Followup-To: header.
3854
3855         `Followup-To: poster'
3856 sends your response via e-mail instead of news.
3857
3858 A typical situation where `Followup-To: poster' is used is when the author
3859 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3860               (setq message-this-is-news nil
3861                     distribution nil
3862                     follow-to (list (cons 'To (or mrt from ""))))
3863             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
3864          (t
3865           (if (or (equal followup-to newsgroups)
3866                   (not (eq message-use-followup-to 'ask))
3867                   (message-y-or-n-p
3868                    (concat "Obey Followup-To: " followup-to "? ") t "\
3869 You should normally obey the Followup-To: header.
3870
3871         `Followup-To: " followup-to "'
3872 directs your response to " (if (string-match "," followup-to)
3873                                "the specified newsgroups"
3874                              "that newsgroup only") ".
3875
3876 If a message is posted to several newsgroups, Followup-To is often
3877 used to direct the following discussion to one newsgroup only,
3878 because discussions that are spread over several newsgroup tend to
3879 be fragmented and very difficult to follow.
3880
3881 Also, some source/announcement newsgroups are not indented for discussion;
3882 responses here are directed to other newsgroups."))
3883               (setq follow-to (list (cons 'Newsgroups followup-to)))
3884             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
3885        ;; Handle Mail-Followup-To, followup via e-mail.
3886        ((and mft
3887              (or (not (eq message-use-mail-followup-to 'ask))
3888                  (message-y-or-n-p
3889                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
3890 You should normally obey the Mail-Followup-To: header.
3891
3892         `Mail-Followup-To: " mft "'
3893 directs your response to " (if (string-match "," mft)
3894                                "the specified addresses"
3895                              "that address only") " instead of news.
3896
3897 A typical situation where Mail-Followup-To is used is when the author thinks
3898 that further discussion should take place only in "
3899                              (if (string-match "," mft)
3900                                  "the specified mailing lists"
3901                                "that mailing list") ".")))
3902         (setq message-this-is-news nil
3903               distribution nil
3904               follow-to (list (cons 'To mft))))
3905        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
3906        (t
3907         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
3908
3909     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3910
3911     (setq message-reply-headers
3912           (vector 0 subject from date message-id references 0 0 ""))
3913
3914     (message-setup
3915      `((Subject . ,subject)
3916        ,@follow-to
3917        ,@(and mct (list (cons 'Cc mct)))
3918        ,@(and distribution (list (cons 'Distribution distribution)))
3919        ,@(if (or references message-id)
3920              `((References . ,(concat (or references "") (and references " ")
3921                                       (or message-id ""))))))
3922      cur)))
3923
3924 ;;;###autoload
3925 (defun message-cancel-news ()
3926   "Cancel an article you posted."
3927   (interactive)
3928   (unless (message-news-p)
3929     (error "This is not a news article; canceling is impossible"))
3930   (when (yes-or-no-p "Do you really want to cancel this article? ")
3931     (let (from newsgroups message-id distribution buf sender)
3932       (save-excursion
3933         ;; Get header info. from original article.
3934         (save-restriction
3935           (message-narrow-to-head)
3936           (setq from (message-fetch-field "from")
3937                 sender (message-fetch-field "sender")
3938                 newsgroups (message-fetch-field "newsgroups")
3939                 message-id (message-fetch-field "message-id" t)
3940                 distribution (message-fetch-field "distribution")))
3941         ;; Make sure that this article was written by the user.
3942         (unless (or (and sender
3943                          (string-equal
3944                           (downcase sender)
3945                           (downcase (message-make-sender))))
3946                     (string-equal
3947                      (downcase (cadr (std11-extract-address-components
3948                                       from)))
3949                      (downcase (cadr (std11-extract-address-components
3950                                       (message-make-from))))))
3951           (error "This article is not yours"))
3952         ;; Make control message.
3953         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3954         (buffer-disable-undo (current-buffer))
3955         (erase-buffer)
3956         (insert "Newsgroups: " newsgroups "\n"
3957                 "From: " (message-make-from) "\n"
3958                 "Subject: cmsg cancel " message-id "\n"
3959                 "Control: cancel " message-id "\n"
3960                 (if distribution
3961                     (concat "Distribution: " distribution "\n")
3962                   "")
3963                 mail-header-separator "\n"
3964                 message-cancel-message)
3965         (message "Canceling your article...")
3966         (if (let ((message-syntax-checks
3967                    'dont-check-for-anything-just-trust-me)
3968                   (message-encoding-buffer (current-buffer))
3969                   (message-edit-buffer (current-buffer)))
3970               (message-send-news))
3971             (message "Canceling your article...done"))
3972         (kill-buffer buf)))))
3973
3974 ;;;###autoload
3975 (defun message-supersede ()
3976   "Start composing a message to supersede the current message.
3977 This is done simply by taking the old article and adding a Supersedes
3978 header line with the old Message-ID."
3979   (interactive)
3980   (let ((cur (current-buffer))
3981         (sender (message-fetch-field "sender"))
3982         (from (message-fetch-field "from")))
3983     ;; Check whether the user owns the article that is to be superseded.
3984     (unless (or (and sender
3985                      (string-equal
3986                       (downcase sender)
3987                       (downcase (message-make-sender))))
3988                 (string-equal
3989                  (downcase (cadr (std11-extract-address-components from)))
3990                  (downcase (cadr (std11-extract-address-components
3991                                   (message-make-from))))))
3992       (error "This article is not yours"))
3993     ;; Get a normal message buffer.
3994     (message-pop-to-buffer (message-buffer-name "supersede"))
3995     (insert-buffer-substring cur)
3996     (message-narrow-to-head)
3997     ;; Remove unwanted headers.
3998     (when message-ignored-supersedes-headers
3999       (message-remove-header message-ignored-supersedes-headers t))
4000     (goto-char (point-min))
4001     (if (not (re-search-forward "^Message-ID: " nil t))
4002         (error "No Message-ID in this article")
4003       (replace-match "Supersedes: " t t))
4004     (goto-char (point-max))
4005     (insert mail-header-separator)
4006     (widen)
4007     (forward-line 1)))
4008
4009 ;;;###autoload
4010 (defun message-recover ()
4011   "Reread contents of current buffer from its last auto-save file."
4012   (interactive)
4013   (let ((file-name (make-auto-save-file-name)))
4014     (cond ((save-window-excursion
4015              (if (not (eq system-type 'vax-vms))
4016                  (with-output-to-temp-buffer "*Directory*"
4017                    (buffer-disable-undo standard-output)
4018                    (let ((default-directory "/"))
4019                      (call-process
4020                       "ls" nil standard-output nil "-l" file-name))))
4021              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4022            (let ((buffer-read-only nil))
4023              (erase-buffer)
4024              (insert-file-contents file-name nil)))
4025           (t (error "message-recover cancelled")))))
4026
4027 ;;; Washing Subject:
4028
4029 (defun message-wash-subject (subject)
4030   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4031   (with-temp-buffer
4032     (insert-string subject)
4033     (goto-char (point-min))
4034     ;; strip Re/Fwd stuff off the beginning
4035     (while (re-search-forward
4036             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4037       (replace-match ""))
4038
4039     ;; and gnus-style forwards [foo@bar.com] subject
4040     (goto-char (point-min))
4041     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4042       (replace-match ""))
4043
4044     ;; and off the end
4045     (goto-char (point-max))
4046     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4047       (replace-match ""))
4048
4049     ;; and finally, any whitespace that was left-over
4050     (goto-char (point-min))
4051     (while (re-search-forward "^[ \t]+" nil t)
4052       (replace-match ""))
4053     (goto-char (point-max))
4054     (while (re-search-backward "[ \t]+$" nil t)
4055       (replace-match ""))
4056
4057     (buffer-string)))
4058     
4059 ;;; Forwarding messages.
4060
4061 (defun message-forward-subject-author-subject (subject)
4062   "Generate a subject for a forwarded message.
4063 The form is: [Source] Subject, where if the original message was mail,
4064 Source is the sender, and if the original message was news, Source is
4065 the list of newsgroups is was posted to."
4066   (concat "["
4067           (or (message-fetch-field
4068                (if (message-news-p) "newsgroups" "from"))
4069               "(nowhere)")
4070           "] " subject))
4071
4072 (defun message-forward-subject-fwd (subject)
4073   "Generate a subject for a forwarded message.
4074 The form is: Fwd: Subject, where Subject is the original subject of
4075 the message."
4076   (concat "Fwd: " subject))
4077
4078 (defun message-make-forward-subject ()
4079   "Return a Subject header suitable for the message in the current buffer."
4080   (save-excursion
4081     (save-restriction
4082       (current-buffer)
4083       (message-narrow-to-head)
4084       (let ((funcs message-make-forward-subject-function)
4085             (subject (if message-wash-forwarded-subjects
4086                          (message-wash-subject
4087                           (or (eword-decode-unstructured-field-body
4088                                (message-fetch-field "Subject")) ""))
4089                        (or (eword-decode-unstructured-field-body
4090                             (message-fetch-field "Subject")) ""))))
4091         ;; Make sure funcs is a list.
4092         (and funcs
4093              (not (listp funcs))
4094              (setq funcs (list funcs)))
4095         ;; Apply funcs in order, passing subject generated by previous
4096         ;; func to the next one.
4097         (while funcs
4098           (when (message-functionp (car funcs))
4099             (setq subject (funcall (car funcs) subject)))
4100           (setq funcs (cdr funcs)))
4101         subject))))
4102
4103 ;;;###autoload
4104 (defun message-forward (&optional news)
4105   "Forward the current message via mail.
4106 Optional NEWS will use news to forward instead of mail."
4107   (interactive "P")
4108   (let ((cur (current-buffer))
4109         (subject (message-make-forward-subject))
4110         art-beg)
4111     (if news (message-news nil subject) (message-mail nil subject))
4112     ;; Put point where we want it before inserting the forwarded
4113     ;; message.
4114     (if message-signature-before-forwarded-message
4115         (goto-char (point-max))
4116       (message-goto-body))
4117     ;; Make sure we're at the start of the line.
4118     (unless (eolp)
4119       (insert "\n"))
4120     ;; Narrow to the area we are to insert.
4121     (narrow-to-region (point) (point))
4122     ;; Insert the separators and the forwarded buffer.
4123     (insert message-forward-start-separator)
4124     (setq art-beg (point))
4125     (insert-buffer-substring cur)
4126     (goto-char (point-max))
4127     (insert message-forward-end-separator)
4128     (set-text-properties (point-min) (point-max) nil)
4129     ;; Remove all unwanted headers.
4130     (goto-char art-beg)
4131     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4132                                   (1- (point))
4133                                 (point)))
4134     (goto-char (point-min))
4135     (message-remove-header message-included-forward-headers t nil t)
4136     (widen)
4137     (message-position-point)))
4138
4139 ;;;###autoload
4140 (defun message-resend (address)
4141   "Resend the current article to ADDRESS."
4142   (interactive "sResend message to: ")
4143   (message "Resending message to %s..." address)
4144   (save-excursion
4145     (let ((cur (current-buffer))
4146           beg)
4147       ;; We first set up a normal mail buffer.
4148       (set-buffer (get-buffer-create " *message resend*"))
4149       (buffer-disable-undo (current-buffer))
4150       (erase-buffer)
4151       ;; avoid to turn-on-mime-edit
4152       (let (message-setup-hook)
4153         (message-setup `((To . ,address)))
4154         )
4155       ;; Insert our usual headers.
4156       (message-generate-headers '(From Date To))
4157       (message-narrow-to-headers)
4158       ;; Rename them all to "Resent-*".
4159       (while (re-search-forward "^[A-Za-z]" nil t)
4160         (forward-char -1)
4161         (insert "Resent-"))
4162       (widen)
4163       (forward-line)
4164       (delete-region (point) (point-max))
4165       (setq beg (point))
4166       ;; Insert the message to be resent.
4167       (insert-buffer-substring cur)
4168       (goto-char (point-min))
4169       (search-forward "\n\n")
4170       (forward-char -1)
4171       (save-restriction
4172         (narrow-to-region beg (point))
4173         (message-remove-header message-ignored-resent-headers t)
4174         (goto-char (point-max)))
4175       (insert mail-header-separator)
4176       ;; Rename all old ("Also-")Resent headers.
4177       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4178         (beginning-of-line)
4179         (insert "Also-"))
4180       ;; Quote any "From " lines at the beginning.
4181       (goto-char beg)
4182       (when (looking-at "From ")
4183         (replace-match "X-From-Line: "))
4184       ;; Send it.
4185       (let ((message-encoding-buffer (current-buffer))
4186             (message-edit-buffer (current-buffer)))
4187         (message-send-mail))
4188       (kill-buffer (current-buffer)))
4189     (message "Resending message to %s...done" address)))
4190
4191 ;;;###autoload
4192 (defun message-bounce ()
4193   "Re-mail the current message.
4194 This only makes sense if the current message is a bounce message than
4195 contains some mail you have written which has been bounced back to
4196 you."
4197   (interactive)
4198   (let ((cur (current-buffer))
4199         boundary)
4200     (message-pop-to-buffer (message-buffer-name "bounce"))
4201     (insert-buffer-substring cur)
4202     (undo-boundary)
4203     (message-narrow-to-head)
4204     (if (and (message-fetch-field "MIME-Version")
4205              (setq boundary (message-fetch-field "Content-Type")))
4206         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4207             (setq boundary (concat (match-string 1 boundary) " *\n"
4208                                    "Content-Type: message/rfc822"))
4209           (setq boundary nil)))
4210     (widen)
4211     (goto-char (point-min))
4212     (search-forward "\n\n" nil t)
4213     (or (and boundary
4214              (re-search-forward boundary nil t)
4215              (forward-line 2))
4216         (and (re-search-forward message-unsent-separator nil t)
4217              (forward-line 1))
4218         (re-search-forward "^Return-Path:.*\n" nil t))
4219     ;; We remove everything before the bounced mail.
4220     (delete-region
4221      (point-min)
4222      (if (re-search-forward "^[^ \n\t]+:" nil t)
4223          (match-beginning 0)
4224        (point)))
4225     (save-restriction
4226       (message-narrow-to-head)
4227       (message-remove-header message-ignored-bounced-headers t)
4228       (goto-char (point-max))
4229       (insert mail-header-separator))
4230     (message-position-point)))
4231
4232 ;;;
4233 ;;; Interactive entry points for new message buffers.
4234 ;;;
4235
4236 ;;;###autoload
4237 (defun message-mail-other-window (&optional to subject)
4238   "Like `message-mail' command, but display mail buffer in another window."
4239   (interactive)
4240   (let ((pop-up-windows t)
4241         (special-display-buffer-names nil)
4242         (special-display-regexps nil)
4243         (same-window-buffer-names nil)
4244         (same-window-regexps nil))
4245     (message-pop-to-buffer (message-buffer-name "mail" to)))
4246   (let ((message-this-is-mail t))
4247     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4248
4249 ;;;###autoload
4250 (defun message-mail-other-frame (&optional to subject)
4251   "Like `message-mail' command, but display mail buffer in another frame."
4252   (interactive)
4253   (let ((pop-up-frames t)
4254         (special-display-buffer-names nil)
4255         (special-display-regexps nil)
4256         (same-window-buffer-names nil)
4257         (same-window-regexps nil))
4258     (message-pop-to-buffer (message-buffer-name "mail" to)))
4259   (let ((message-this-is-mail t))
4260     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4261
4262 ;;;###autoload
4263 (defun message-news-other-window (&optional newsgroups subject)
4264   "Start editing a news article to be sent."
4265   (interactive)
4266   (let ((pop-up-windows t)
4267         (special-display-buffer-names nil)
4268         (special-display-regexps nil)
4269         (same-window-buffer-names nil)
4270         (same-window-regexps nil))
4271     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4272   (let ((message-this-is-news t))
4273     (message-setup `((Newsgroups . ,(or newsgroups ""))
4274                      (Subject . ,(or subject ""))))))
4275
4276 ;;;###autoload
4277 (defun message-news-other-frame (&optional newsgroups subject)
4278   "Start editing a news article to be sent."
4279   (interactive)
4280   (let ((pop-up-frames t)
4281         (special-display-buffer-names nil)
4282         (special-display-regexps nil)
4283         (same-window-buffer-names nil)
4284         (same-window-regexps nil))
4285     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4286   (let ((message-this-is-news t))
4287     (message-setup `((Newsgroups . ,(or newsgroups ""))
4288                      (Subject . ,(or subject ""))))))
4289
4290 ;;; underline.el
4291
4292 ;; This code should be moved to underline.el (from which it is stolen).
4293
4294 ;;;###autoload
4295 (defun bold-region (start end)
4296   "Bold all nonblank characters in the region.
4297 Works by overstriking characters.
4298 Called from program, takes two arguments START and END
4299 which specify the range to operate on."
4300   (interactive "r")
4301   (save-excursion
4302     (let ((end1 (make-marker)))
4303       (move-marker end1 (max start end))
4304       (goto-char (min start end))
4305       (while (< (point) end1)
4306         (or (looking-at "[_\^@- ]")
4307             (insert (following-char) "\b"))
4308         (forward-char 1)))))
4309
4310 ;;;###autoload
4311 (defun unbold-region (start end)
4312   "Remove all boldness (overstruck characters) in the region.
4313 Called from program, takes two arguments START and END
4314 which specify the range to operate on."
4315   (interactive "r")
4316   (save-excursion
4317     (let ((end1 (make-marker)))
4318       (move-marker end1 (max start end))
4319       (goto-char (min start end))
4320       (while (re-search-forward "\b" end1 t)
4321         (if (eq (following-char) (char-after (- (point) 2)))
4322             (delete-char -2))))))
4323
4324 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4325
4326 ;; Support for toolbar
4327 (when (string-match "XEmacs\\|Lucid" emacs-version)
4328   (require 'messagexmas))
4329
4330 ;;; Group name completion.
4331
4332 (defvar message-newgroups-header-regexp
4333   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4334   "Regexp that match headers that lists groups.")
4335
4336 (defun message-tab ()
4337   "Expand group names in Newsgroups and Followup-To headers.
4338 Do a `tab-to-tab-stop' if not in those headers."
4339   (interactive)
4340   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4341         (mail-abbrev-in-expansion-header-p))
4342       (message-expand-group)
4343     (tab-to-tab-stop)))
4344
4345 (defvar gnus-active-hashtb)
4346 (defun message-expand-group ()
4347   "Expand the group name under point."
4348   (let* ((b (save-excursion
4349               (save-restriction
4350                 (narrow-to-region
4351                  (save-excursion
4352                    (beginning-of-line)
4353                    (skip-chars-forward "^:")
4354                    (1+ (point)))
4355                  (point))
4356                 (skip-chars-backward "^, \t\n") (point))))
4357          (completion-ignore-case t)
4358          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4359                                             (point))))
4360          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4361          (completions (all-completions string hashtb))
4362          comp)
4363     (delete-region b (point))
4364     (cond
4365      ((= (length completions) 1)
4366       (if (string= (car completions) string)
4367           (progn
4368             (insert string)
4369             (message "Only matching group"))
4370         (insert (car completions))))
4371      ((and (setq comp (try-completion string hashtb))
4372            (not (string= comp string)))
4373       (insert comp))
4374      (t
4375       (insert string)
4376       (if (not comp)
4377           (message "No matching groups")
4378         (save-selected-window
4379           (pop-to-buffer "*Completions*")
4380           (buffer-disable-undo (current-buffer))
4381           (let ((buffer-read-only nil))
4382             (erase-buffer)
4383             (let ((standard-output (current-buffer)))
4384               (display-completion-list (sort completions 'string<)))
4385             (goto-char (point-min))
4386             (delete-region (point) (progn (forward-line 3) (point))))))))))
4387
4388 ;;; Help stuff.
4389
4390 (defun message-talkative-question (ask question show &rest text)
4391   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4392 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4393 The following arguments may contain lists of values."
4394   (if (and show
4395            (setq text (message-flatten-list text)))
4396       (save-window-excursion
4397         (save-excursion
4398           (with-output-to-temp-buffer " *MESSAGE information message*"
4399             (set-buffer " *MESSAGE information message*")
4400             (mapcar 'princ text)
4401             (goto-char (point-min))))
4402         (funcall ask question))
4403     (funcall ask question)))
4404
4405 (defun message-flatten-list (list)
4406   "Return a new, flat list that contains all elements of LIST.
4407
4408 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4409 => (1 2 3 4 5 6 7)"
4410   (cond ((consp list)
4411          (apply 'append (mapcar 'message-flatten-list list)))
4412         (list
4413          (list list))))
4414
4415 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4416   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4417 Then clone the local variables and values from the old buffer to the
4418 new one, cloning only the locals having a substring matching the
4419 regexp varstr."
4420   (let ((oldbuf (current-buffer)))
4421     (save-excursion
4422       (set-buffer (generate-new-buffer name))
4423       (message-clone-locals oldbuf)
4424       (current-buffer))))
4425
4426 (defun message-clone-locals (buffer)
4427   "Clone the local variables from BUFFER to the current buffer."
4428   (let ((locals (save-excursion
4429                   (set-buffer buffer)
4430                   (buffer-local-variables)))
4431         (regexp "^gnus\\|^nn\\|^message"))
4432     (mapcar
4433      (lambda (local)
4434        (when (and (consp local)
4435                   (car local)
4436                   (string-match regexp (symbol-name (car local))))
4437          (ignore-errors
4438            (set (make-local-variable (car local))
4439                 (cdr local)))))
4440      locals)))
4441
4442
4443 ;;; @ for MIME Edit mode
4444 ;;;
4445
4446 (defun message-maybe-setup-default-charset ()
4447   (let ((charset
4448          (and (boundp 'gnus-summary-buffer)
4449               (buffer-live-p gnus-summary-buffer)
4450               (save-excursion
4451                 (set-buffer gnus-summary-buffer)
4452                 default-mime-charset))))
4453     (if charset
4454         (progn
4455           (make-local-variable 'default-mime-charset)
4456           (setq default-mime-charset charset)
4457           ))))
4458
4459 (defun message-maybe-encode ()
4460   (when message-mime-mode
4461     (run-hooks 'mime-edit-translate-hook)
4462     (if (catch 'mime-edit-error
4463           (save-excursion
4464             (mime-edit-translate-body)
4465             ))
4466         (error "Translation error!")
4467       )
4468     (end-of-invisible)
4469     (run-hooks 'mime-edit-exit-hook)
4470     ))
4471
4472 ;;; XXX: currently broken; message-yank-original resets message-reply-buffer.
4473 (defun message-mime-insert-article (&optional message)
4474   (interactive)
4475   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4476         (message-reply-buffer gnus-original-article-buffer)
4477         )
4478     (message-yank-original nil)
4479     ))
4480
4481 (set-alist 'mime-edit-message-inserter-alist
4482            'message-mode (function message-mime-insert-article))
4483
4484 ;;; Miscellaneous functions
4485
4486 ;; stolen (and renamed) from nnheader.el
4487 (defun message-replace-chars-in-string (string from to)
4488   "Replace characters in STRING from FROM to TO."
4489   (let ((string (substring string 0))   ;Copy string.
4490         (len (length string))
4491         (idx 0))
4492     ;; Replace all occurrences of FROM with TO.
4493     (while (< idx len)
4494       (when (= (aref string idx) from)
4495         (aset string idx to))
4496       (setq idx (1+ idx)))
4497     string))
4498
4499 (run-hooks 'message-load-hook)
4500
4501 (provide 'message)
4502
4503 ;;; message.el ends here