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