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