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