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