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