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