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