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