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