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