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