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