Sync up with nana-gnus-6_13_2.
[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   (if (catch 'message-sending-cancel
2145         ;; Disabled test.
2146         (unless (or (buffer-modified-p)
2147                     (message-check-element 'unchanged)
2148                     (y-or-n-p "No changes in the buffer; really send? "))
2149           (throw 'message-sending-cancel t))
2150         ;; Make it possible to undo the coming changes.
2151         (undo-boundary)
2152         (let ((inhibit-read-only t))
2153           (put-text-property (point-min) (point-max) 'read-only nil))
2154         (run-hooks 'message-send-hook)
2155         (message "Sending...")
2156         (let ((message-encoding-buffer
2157                (message-generate-new-buffer-clone-locals " message encoding"))
2158               (message-edit-buffer (current-buffer))
2159               (message-mime-mode mime-edit-mode-flag)
2160               (alist message-send-method-alist)
2161               (success t)
2162               elem sent)
2163           (unwind-protect
2164               (if (save-excursion
2165                     (set-buffer message-encoding-buffer)
2166                     (erase-buffer)
2167                     (insert-buffer message-edit-buffer)
2168                     (funcall message-encode-function)
2169                     (message-fix-before-sending)
2170                     (while (and success
2171                                 (setq elem (pop alist)))
2172                       (and (funcall (cadr elem))
2173                            (and (or (not (memq (car elem)
2174                                                message-sent-message-via))
2175                                     (y-or-n-p
2176                                      (format
2177                                       "Already sent message via %s; resend? "
2178                                       (car elem))))
2179                                 (setq success (funcall (caddr elem) arg)))
2180                            (setq sent t)))
2181                     (not (and success sent)))
2182                   (throw 'message-sending-cancel t)
2183                 (message-do-fcc)
2184                 (run-hooks 'message-sent-hook)
2185                 (message "Sending...done")
2186                 ;; Mark the buffer as unmodified and delete auto-save.
2187                 (set-buffer-modified-p nil)
2188                 (delete-auto-save-file-if-necessary t)
2189                 (message-disassociate-draft)
2190                 ;; Delete other mail buffers and stuff.
2191                 (message-do-send-housekeeping)
2192                 (message-do-actions message-send-actions)
2193                 nil)
2194             (kill-buffer message-encoding-buffer))))
2195       (progn
2196         (message "Canceled")
2197         nil)
2198     ;; Return success.
2199     t))
2200
2201 (defun message-send-via-mail (arg)
2202   "Send the current message via mail."
2203   (message-send-mail arg))
2204
2205 (defun message-send-via-news (arg)
2206   "Send the current message via news."
2207   (message-send-news arg))
2208
2209 (defun message-fix-before-sending ()
2210   "Do various things to make the message nice before sending it."
2211   ;; Make sure there's a newline at the end of the message.
2212   (goto-char (point-max))
2213   (unless (bolp)
2214     (insert "\n"))
2215   ;; Make all invisible text visible.
2216   ;;(when (text-property-any (point-min) (point-max) 'invisible t)
2217   ;;  (put-text-property (point-min) (point-max) 'invisible nil)
2218   ;;  (unless (yes-or-no-p "Invisible text found and made visible; continue posting?")
2219   ;;    (error "Invisible text found and made visible")))
2220   )
2221
2222 (defun message-add-action (action &rest types)
2223   "Add ACTION to be performed when doing an exit of type TYPES."
2224   (let (var)
2225     (while types
2226       (set (setq var (intern (format "message-%s-actions" (pop types))))
2227            (nconc (symbol-value var) (list action))))))
2228
2229 (defun message-do-actions (actions)
2230   "Perform all actions in ACTIONS."
2231   ;; Now perform actions on successful sending.
2232   (while actions
2233     (ignore-errors
2234       (cond
2235        ;; A simple function.
2236        ((message-functionp (car actions))
2237         (funcall (car actions)))
2238        ;; Something to be evaled.
2239        (t
2240         (eval (car actions)))))
2241     (pop actions)))
2242
2243 (defsubst message-maybe-split-and-send-mail ()
2244   "Split a message if necessary, and send it via mail.
2245 Returns nil if sending succeeded, returns any string if sending failed.
2246 This sub function is for exclusive use of `message-send-mail'."
2247   (let ((mime-edit-split-ignored-field-regexp
2248          mime-edit-split-ignored-field-regexp)
2249         (case-fold-search t)
2250         failure)
2251     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
2252       (setq mime-edit-split-ignored-field-regexp
2253             (concat (substring mime-edit-split-ignored-field-regexp
2254                                0 (match-beginning 0))
2255                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
2256                     "_so_don't_rape_it!"
2257                     (substring mime-edit-split-ignored-field-regexp
2258                                (match-end 0)))))
2259     (setq failure
2260           (or
2261            (catch 'message-sending-mail-failure
2262              (mime-edit-maybe-split-and-send
2263               (function
2264                (lambda ()
2265                  (interactive)
2266                  (save-restriction
2267                    (std11-narrow-to-header mail-header-separator)
2268                    (goto-char (point-min))
2269                    (when (re-search-forward "^Message-ID:" nil t)
2270                      (delete-region (match-end 0) (std11-field-end))
2271                      (insert " " (message-make-message-id))))
2272                  (condition-case err
2273                      (funcall message-send-mail-function)
2274                    (error
2275                     (throw 'message-sending-mail-failure err))))))
2276              nil)
2277            (condition-case err
2278                (progn
2279                  (funcall message-send-mail-function)
2280                  nil)
2281              (error err))))
2282     (when failure
2283       (if (eq 'error (car failure))
2284           (cadr failure)
2285         (prin1-to-string failure)))))
2286
2287 (defun message-send-mail (&optional arg)
2288   (require 'mail-utils)
2289   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2290         (case-fold-search nil)
2291         (news (message-news-p))
2292         failure)
2293     (save-restriction
2294       (message-narrow-to-headers)
2295       ;; Insert some headers.
2296       (let ((message-deletable-headers
2297              (if news nil message-deletable-headers)))
2298         (message-generate-headers message-required-mail-headers))
2299       ;; Let the user do all of the above.
2300       (run-hooks 'message-header-hook)
2301       (when (functionp message-header-encode-function)
2302         (funcall message-header-encode-function))
2303       (run-hooks 'message-header-encoded-hook))
2304     (if (not (message-check-mail-syntax))
2305         (progn
2306           (message "")
2307           nil)
2308       (unwind-protect
2309           (save-excursion
2310             (set-buffer tembuf)
2311             (erase-buffer)
2312             (insert-buffer message-encoding-buffer)
2313             ;; Remove some headers.
2314             (save-restriction
2315               (message-narrow-to-headers)
2316               ;; Remove some headers.
2317               (message-remove-header message-ignored-mail-headers t))
2318             (goto-char (point-max))
2319             ;; require one newline at the end.
2320             (or (eq (char-before) ?\n)
2321                 (insert ?\n))
2322             (when (and news
2323                        (or (message-fetch-field "cc")
2324                            (message-fetch-field "to")))
2325               (message-insert-courtesy-copy))
2326             (setq failure (message-maybe-split-and-send-mail)))
2327         (kill-buffer tembuf))
2328       (set-buffer message-edit-buffer)
2329       (if failure
2330           (progn
2331             (message "Couldn't send message via mail: %s" failure)
2332             nil)
2333         (push 'mail message-sent-message-via)))))
2334
2335 (defun message-send-mail-with-sendmail ()
2336   "Send off the prepared buffer with sendmail."
2337   (let ((errbuf (if message-interactive
2338                     (generate-new-buffer " sendmail errors")
2339                   0))
2340         resend-to-addresses delimline)
2341     (let ((case-fold-search t))
2342       (save-restriction
2343         (message-narrow-to-headers)
2344         (setq resend-to-addresses (message-fetch-field "resent-to")))
2345       ;; Change header-delimiter to be what sendmail expects.
2346       (goto-char (point-min))
2347       (re-search-forward
2348        (concat "^" (regexp-quote mail-header-separator) "\n"))
2349       (replace-match "\n")
2350       (backward-char 1)
2351       (setq delimline (point-marker))
2352       (run-hooks 'message-send-mail-hook)
2353       ;; Insert an extra newline if we need it to work around
2354       ;; Sun's bug that swallows newlines.
2355       (goto-char (1+ delimline))
2356       (when (eval message-mailer-swallows-blank-line)
2357         (newline))
2358       (when message-interactive
2359         (save-excursion
2360           (set-buffer errbuf)
2361           (erase-buffer))))
2362     (let ((default-directory "/"))
2363       (as-binary-process
2364        (apply 'call-process-region
2365               (append (list (point-min) (point-max)
2366                             (if (boundp 'sendmail-program)
2367                                 sendmail-program
2368                               "/usr/lib/sendmail")
2369                             nil errbuf nil "-oi")
2370                       ;; Always specify who from,
2371                       ;; since some systems have broken sendmails.
2372                       ;; But some systems are more broken with -f, so
2373                       ;; we'll let users override this.
2374                       (if (null message-sendmail-f-is-evil)
2375                           (list "-f" (user-login-name)))
2376                       ;; These mean "report errors by mail"
2377                       ;; and "deliver in background".
2378                       (if (null message-interactive) '("-oem" "-odb"))
2379                       ;; Get the addresses from the message
2380                       ;; unless this is a resend.
2381                       ;; We must not do that for a resend
2382                       ;; because we would find the original addresses.
2383                       ;; For a resend, include the specific addresses.
2384                       (if resend-to-addresses
2385                           (list resend-to-addresses)
2386                         '("-t"))))))
2387     (when message-interactive
2388       (save-excursion
2389         (set-buffer errbuf)
2390         (goto-char (point-min))
2391         (while (re-search-forward "\n\n* *" nil t)
2392           (replace-match "; "))
2393         (if (not (zerop (buffer-size)))
2394             (error "Sending...failed to %s"
2395                    (buffer-substring (point-min) (point-max)))))
2396       (when (bufferp errbuf)
2397         (kill-buffer errbuf)))))
2398
2399 (defun message-send-mail-with-qmail ()
2400   "Pass the prepared message buffer to qmail-inject.
2401 Refer to the documentation for the variable `message-send-mail-function'
2402 to find out how to use this."
2403   ;; replace the header delimiter with a blank line
2404   (goto-char (point-min))
2405   (re-search-forward
2406    (concat "^" (regexp-quote mail-header-separator) "\n"))
2407   (replace-match "\n")
2408   (run-hooks 'message-send-mail-hook)
2409   ;; send the message
2410   (case
2411       (as-binary-process
2412        (apply
2413         'call-process-region 1 (point-max) message-qmail-inject-program
2414         nil nil nil
2415         ;; qmail-inject's default behaviour is to look for addresses on the
2416         ;; command line; if there're none, it scans the headers.
2417         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2418         ;;
2419         ;; in general, ALL of qmail-inject's defaults are perfect for simply
2420         ;; reading a formatted (i. e., at least a To: or Resent-To header)
2421         ;; message from stdin.
2422         ;;
2423         ;; qmail also has the advantage of not having been raped by
2424         ;; various vendors, so we don't have to allow for that, either --
2425         ;; compare this with message-send-mail-with-sendmail and weep
2426         ;; for sendmail's lost innocence.
2427         ;;
2428         ;; all this is way cool coz it lets us keep the arguments entirely
2429         ;; free for -inject-arguments -- a big win for the user and for us
2430         ;; since we don't have to play that double-guessing game and the user
2431         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2432         message-qmail-inject-args))
2433     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2434     ;; we have to look at the retval instead
2435     (0 nil)
2436     (1   (error "qmail-inject reported permanent failure"))
2437     (111 (error "qmail-inject reported transient failure"))
2438     ;; should never happen
2439     (t   (error "qmail-inject reported unknown failure"))))
2440
2441 (defun message-send-mail-with-mh ()
2442   "Send the prepared message buffer with mh."
2443   (let ((mh-previous-window-config nil)
2444         (name (mh-new-draft-name)))
2445     (setq buffer-file-name name)
2446     ;; MH wants to generate these headers itself.
2447     (when message-mh-deletable-headers
2448       (let ((headers message-mh-deletable-headers))
2449         (while headers
2450           (goto-char (point-min))
2451           (and (re-search-forward
2452                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2453                (message-delete-line))
2454           (pop headers))))
2455     (run-hooks 'message-send-mail-hook)
2456     ;; Pass it on to mh.
2457     (mh-send-letter)))
2458
2459 (defun message-send-mail-with-smtp ()
2460   "Send off the prepared buffer with SMTP."
2461   (require 'smtp) ; XXX
2462   (let ((case-fold-search t)
2463         recipients)
2464     (save-restriction
2465       (message-narrow-to-headers)
2466       (setq recipients
2467             ;; XXX: Should be replaced by better one.
2468             (smtp-deduce-address-list (current-buffer)
2469                                       (point-min) (point-max)))
2470       ;; Remove BCC lines.
2471       (message-remove-header "bcc"))
2472     ;; replace the header delimiter with a blank line.
2473     (goto-char (point-min))
2474     (re-search-forward
2475      (concat "^" (regexp-quote mail-header-separator) "\n"))
2476     (replace-match "\n")
2477     (backward-char 1)
2478     (run-hooks 'message-send-mail-hook)
2479     (if recipients
2480         (let ((result (smtp-via-smtp user-mail-address
2481                                      recipients
2482                                      (current-buffer))))
2483           (unless (eq result t)
2484             (error "Sending failed; " result)))
2485       (error "Sending failed; no recipients"))))
2486
2487 (defsubst message-maybe-split-and-send-news (method)
2488   "Split a message if necessary, and send it via news.
2489 Returns nil if sending succeeded, returns t if sending failed.
2490 This sub function is for exclusive use of `message-send-news'."
2491   (let ((mime-edit-split-ignored-field-regexp
2492          mime-edit-split-ignored-field-regexp)
2493         (case-fold-search t))
2494     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
2495       (setq mime-edit-split-ignored-field-regexp
2496             (concat (substring mime-edit-split-ignored-field-regexp
2497                                0 (match-beginning 0))
2498                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
2499                     "_so_don't_rape_it!"
2500                     (substring mime-edit-split-ignored-field-regexp
2501                                (match-end 0)))))
2502     (or
2503      (catch 'message-sending-news-failure
2504        (mime-edit-maybe-split-and-send
2505         (function
2506          (lambda ()
2507            (interactive)
2508            (save-restriction
2509              (std11-narrow-to-header mail-header-separator)
2510              (goto-char (point-min))
2511              (when (re-search-forward "^Message-ID:" nil t)
2512                (delete-region (match-end 0) (std11-field-end))
2513                (insert " " (message-make-message-id))))
2514            (unless (funcall message-send-news-function method)
2515              (throw 'message-sending-news-failure t)))))
2516        nil)
2517      (not (funcall message-send-news-function method)))))
2518
2519 (defun message-send-news (&optional arg)
2520   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2521         (case-fold-search nil)
2522         (method (if (message-functionp message-post-method)
2523                     (funcall message-post-method arg)
2524                   message-post-method))
2525         (message-syntax-checks
2526          (if arg
2527              (cons '(existing-newsgroups . disabled)
2528                    message-syntax-checks)
2529            message-syntax-checks))
2530         result)
2531     (save-restriction
2532       (message-narrow-to-headers)
2533       ;; Insert some headers.
2534       (message-generate-headers message-required-news-headers)
2535       ;; Let the user do all of the above.
2536       (run-hooks 'message-header-hook)
2537       (when (functionp message-header-encode-function)
2538         (funcall message-header-encode-function))
2539       (run-hooks 'message-header-encoded-hook))
2540     (message-cleanup-headers)
2541     (if (not (message-check-news-syntax))
2542         nil
2543       (unwind-protect
2544           (save-excursion
2545             (set-buffer tembuf)
2546             (buffer-disable-undo (current-buffer))
2547             (erase-buffer)
2548             (insert-buffer message-encoding-buffer)
2549             ;; Remove some headers.
2550             (save-restriction
2551               (message-narrow-to-headers)
2552               ;; Remove some headers.
2553               (message-remove-header message-ignored-news-headers t))
2554             (goto-char (point-max))
2555             ;; require one newline at the end.
2556             (or (eq (char-before) ?\n)
2557                 (insert ?\n))
2558             (setq result (message-maybe-split-and-send-news method)))
2559         (kill-buffer tembuf))
2560       (set-buffer message-edit-buffer)
2561       (if result
2562           (progn
2563             (message "Couldn't send message via news: %s"
2564                      (nnheader-get-report (car method)))
2565             nil)
2566         (push 'news message-sent-message-via)))))
2567
2568 ;; 1997-09-29 by MORIOKA Tomohiko
2569 (defun message-send-news-with-gnus (method)
2570   (let ((case-fold-search t))
2571     ;; Remove the delimiter.
2572     (goto-char (point-min))
2573     (re-search-forward
2574      (concat "^" (regexp-quote mail-header-separator) "\n"))
2575     (replace-match "\n")
2576     (backward-char 1)
2577     (run-hooks 'message-send-news-hook)
2578     ;;(require (car method))
2579     ;;(funcall (intern (format "%s-open-server" (car method)))
2580     ;;(cadr method) (cddr method))
2581     ;;(setq result
2582     ;;    (funcall (intern (format "%s-request-post" (car method)))
2583     ;;             (cadr method)))
2584     (gnus-open-server method)
2585     (gnus-request-post method)
2586     ))
2587
2588 ;;;
2589 ;;; Header generation & syntax checking.
2590 ;;;
2591
2592 (defmacro message-check (type &rest forms)
2593   "Eval FORMS if TYPE is to be checked."
2594   `(or (message-check-element ,type)
2595        (save-excursion
2596          ,@forms)))
2597
2598 (put 'message-check 'lisp-indent-function 1)
2599 (put 'message-check 'edebug-form-spec '(form body))
2600
2601 (defun message-check-element (type)
2602   "Returns non-nil if this type is not to be checked."
2603   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2604       t
2605     (let ((able (assq type message-syntax-checks)))
2606       (and (consp able)
2607            (eq (cdr able) 'disabled)))))
2608
2609 (defun message-check-news-syntax ()
2610   "Check the syntax of the message."
2611   (save-excursion
2612     (save-restriction
2613       (widen)
2614       (and
2615        ;; We narrow to the headers and check them first.
2616        (save-excursion
2617          (save-restriction
2618            (message-narrow-to-headers)
2619            (message-check-news-header-syntax)))
2620        ;; Check the body.
2621        (save-excursion
2622          (set-buffer message-edit-buffer)
2623          (message-check-news-body-syntax))))))
2624
2625 (defun message-check-news-header-syntax ()
2626   (and
2627    ;; Check the Subject header.
2628    (message-check 'subject
2629      (let* ((case-fold-search t)
2630             (subject (message-fetch-field "subject")))
2631        (or
2632         (and subject
2633              (not (string-match "\\`[ \t]*\\'" subject)))
2634         (ignore
2635          (message
2636           "The subject field is empty or missing.  Posting is denied.")))))
2637    ;; Check for commands in Subject.
2638    (message-check 'subject-cmsg
2639      (if (string-match "^cmsg " (message-fetch-field "subject"))
2640          (y-or-n-p
2641           "The control code \"cmsg\" is in the subject.  Really post? ")
2642        t))
2643    ;; Check for multiple identical headers.
2644    (message-check 'multiple-headers
2645      (let (found)
2646        (while (and (not found)
2647                    (re-search-forward "^[^ \t:]+: " nil t))
2648          (save-excursion
2649            (or (re-search-forward
2650                 (concat "^"
2651                         (regexp-quote
2652                          (setq found
2653                                (buffer-substring
2654                                 (match-beginning 0) (- (match-end 0) 2))))
2655                         ":")
2656                 nil t)
2657                (setq found nil))))
2658        (if found
2659            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2660          t)))
2661    ;; Check for Version and Sendsys.
2662    (message-check 'sendsys
2663      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2664          (y-or-n-p
2665           (format "The article contains a %s command.  Really post? "
2666                   (buffer-substring (match-beginning 0)
2667                                     (1- (match-end 0)))))
2668        t))
2669    ;; See whether we can shorten Followup-To.
2670    (message-check 'shorten-followup-to
2671      (let ((newsgroups (message-fetch-field "newsgroups"))
2672            (followup-to (message-fetch-field "followup-to"))
2673            to)
2674        (when (and newsgroups
2675                   (string-match "," newsgroups)
2676                   (not followup-to)
2677                   (not
2678                    (zerop
2679                     (length
2680                      (setq to (completing-read
2681                                "Followups to: (default all groups) "
2682                                (mapcar (lambda (g) (list g))
2683                                        (cons "poster"
2684                                              (message-tokenize-header
2685                                               newsgroups)))))))))
2686          (goto-char (point-min))
2687          (insert "Followup-To: " to "\n"))
2688        t))
2689    ;; Check "Shoot me".
2690    (message-check 'shoot
2691      (if (re-search-forward
2692           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2693          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2694        t))
2695    ;; Check for Approved.
2696    (message-check 'approved
2697      (if (re-search-forward "^Approved:" nil t)
2698          (y-or-n-p "The article contains an Approved header.  Really post? ")
2699        t))
2700    ;; Check the Message-ID header.
2701    (message-check 'message-id
2702      (let* ((case-fold-search t)
2703             (message-id (message-fetch-field "message-id" t)))
2704        (or (not message-id)
2705            ;; Is there an @ in the ID?
2706            (and (string-match "@" message-id)
2707                 ;; Is there a dot in the ID?
2708                 (string-match "@[^.]*\\." message-id)
2709                 ;; Does the ID end with a dot?
2710                 (not (string-match "\\.>" message-id)))
2711            (y-or-n-p
2712             (format "The Message-ID looks strange: \"%s\".  Really post? "
2713                     message-id)))))
2714    ;; Check the Newsgroups & Followup-To headers.
2715    (message-check 'existing-newsgroups
2716      (let* ((case-fold-search t)
2717             (newsgroups (message-fetch-field "newsgroups"))
2718             (followup-to (message-fetch-field "followup-to"))
2719             (groups (message-tokenize-header
2720                      (if followup-to
2721                          (concat newsgroups "," followup-to)
2722                        newsgroups)))
2723             (hashtb (and (boundp 'gnus-active-hashtb)
2724                          gnus-active-hashtb))
2725             errors)
2726        (if (or (not hashtb)
2727                (not (boundp 'gnus-read-active-file))
2728                (not gnus-read-active-file)
2729                (eq gnus-read-active-file 'some))
2730            t
2731          (while groups
2732            (when (and (not (boundp (intern (car groups) hashtb)))
2733                       (not (equal (car groups) "poster")))
2734              (push (car groups) errors))
2735            (pop groups))
2736          (if (not errors)
2737              t
2738            (y-or-n-p
2739             (format
2740              "Really post to %s unknown group%s: %s "
2741              (if (= (length errors) 1) "this" "these")
2742              (if (= (length errors) 1) "" "s")
2743              (mapconcat 'identity errors ", ")))))))
2744    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2745    (message-check 'valid-newsgroups
2746      (let ((case-fold-search t)
2747            (headers '("Newsgroups" "Followup-To"))
2748            header error)
2749        (while (and headers (not error))
2750          (when (setq header (mail-fetch-field (car headers)))
2751            (if (or
2752                 (not
2753                  (string-match
2754                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2755                   header))
2756                 (memq
2757                  nil (mapcar
2758                       (lambda (g)
2759                         (not (string-match "\\.\\'\\|\\.\\." g)))
2760                       (message-tokenize-header header ","))))
2761                (setq error t)))
2762          (unless error
2763            (pop headers)))
2764        (if (not error)
2765            t
2766          (y-or-n-p
2767           (format "The %s header looks odd: \"%s\".  Really post? "
2768                   (car headers) header)))))
2769    (message-check 'repeated-newsgroups
2770      (let ((case-fold-search t)
2771            (headers '("Newsgroups" "Followup-To"))
2772            header error groups group)
2773        (while (and headers
2774                    (not error))
2775          (when (setq header (mail-fetch-field (pop headers)))
2776            (setq groups (message-tokenize-header header ","))
2777            (while (setq group (pop groups))
2778              (when (member group groups)
2779                (setq error group
2780                      groups nil)))))
2781        (if (not error)
2782            t
2783          (y-or-n-p
2784           (format "Group %s is repeated in headers.  Really post? " error)))))
2785    ;; Check the From header.
2786    (message-check 'from
2787      (let* ((case-fold-search t)
2788             (from (message-fetch-field "from"))
2789             (ad (nth 1 (mail-extract-address-components from))))
2790        (cond
2791         ((not from)
2792          (message "There is no From line.  Posting is denied.")
2793          nil)
2794         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2795              (string-match "\\.\\." ad) ;larsi@ifi..uio
2796              (string-match "@\\." ad)   ;larsi@.ifi.uio
2797              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2798              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2799              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2800          (message
2801           "Denied posting -- the From looks strange: \"%s\"." from)
2802          nil)
2803         (t t))))))
2804
2805 (defun message-check-news-body-syntax ()
2806   (and
2807    ;; Check for long lines.
2808    (message-check 'long-lines
2809      (goto-char (point-min))
2810      (re-search-forward
2811       (concat "^" (regexp-quote mail-header-separator) "$"))
2812      (while (and
2813              (progn
2814                (end-of-line)
2815                (< (current-column) 80))
2816              (zerop (forward-line 1))))
2817      (or (bolp)
2818          (eobp)
2819          (y-or-n-p
2820           "You have lines longer than 79 characters.  Really post? ")))
2821    ;; Check whether the article is empty.
2822    (message-check 'empty
2823      (goto-char (point-min))
2824      (re-search-forward
2825       (concat "^" (regexp-quote mail-header-separator) "$"))
2826      (forward-line 1)
2827      (let ((b (point)))
2828        (goto-char (point-max))
2829        (re-search-backward message-signature-separator nil t)
2830        (beginning-of-line)
2831        (or (re-search-backward "[^ \n\t]" b t)
2832            (y-or-n-p "Empty article.  Really post? "))))
2833    ;; Check for control characters.
2834    (message-check 'control-chars
2835      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2836          (y-or-n-p
2837           "The article contains control characters.  Really post? ")
2838        t))
2839    ;; Check 8bit characters.
2840    (message-check '8bit
2841      (message-check-8bit))
2842    ;; Check excessive size.
2843    (message-check 'size
2844      (if (> (buffer-size) 60000)
2845          (y-or-n-p
2846           (format "The article is %d octets long.  Really post? "
2847                   (buffer-size)))
2848        t))
2849    ;; Check whether any new text has been added.
2850    (message-check 'new-text
2851      (or
2852       (not message-checksum)
2853       (not (eq (message-checksum) message-checksum))
2854       (y-or-n-p
2855        "It looks like no new text has been added.  Really post? ")))
2856    ;; Check the length of the signature.
2857    (message-check 'signature
2858      (goto-char (point-max))
2859      (if (or (not (re-search-backward message-signature-separator nil t))
2860              (search-forward message-forward-end-separator nil t))
2861          t
2862        (if (> (count-lines (point) (point-max)) 5)
2863            (y-or-n-p
2864             (format
2865              "Your .sig is %d lines; it should be max 4.  Really post? "
2866              (1- (count-lines (point) (point-max)))))
2867          t)))))
2868
2869 (defun message-check-mail-syntax ()
2870   "Check the syntax of the message."
2871   (save-excursion
2872     (save-restriction
2873       (widen)
2874       (and
2875        ;; We narrow to the headers and check them first.
2876        (save-excursion
2877          (save-restriction
2878            (message-narrow-to-headers)
2879            (message-check-mail-header-syntax)))
2880        ;; Check the body.
2881        (save-excursion
2882          (set-buffer message-edit-buffer)
2883          (message-check-mail-body-syntax))))))
2884
2885 (defun message-check-mail-header-syntax ()
2886   t)
2887
2888 (defun message-check-mail-body-syntax ()
2889   (and
2890    ;; Check 8bit characters.
2891    (message-check '8bit
2892      (message-check-8bit)
2893      )))
2894
2895 (defun message-check-8bit ()
2896   "Check the article contains 8bit characters."
2897   (save-excursion
2898     (set-buffer message-encoding-buffer)
2899     (message-narrow-to-headers)
2900     (let* ((case-fold-search t)
2901            (field-value (message-fetch-field "content-transfer-encoding")))
2902       (if (and field-value
2903                (member (downcase field-value) message-8bit-encoding-list))
2904           t
2905         (widen)
2906         (set-buffer (get-buffer-create " message syntax"))
2907         (erase-buffer)
2908         (goto-char (point-min))
2909         (set-buffer-multibyte nil)
2910         (insert-buffer message-encoding-buffer)
2911         (goto-char (point-min))
2912         (if (re-search-forward "[^\x00-\x7f]" nil t)
2913             (y-or-n-p
2914              "The article contains 8bit characters.  Really post? ")
2915           t)))))
2916
2917 (defun message-checksum ()
2918   "Return a \"checksum\" for the current buffer."
2919   (let ((sum 0))
2920     (save-excursion
2921       (goto-char (point-min))
2922       (re-search-forward
2923        (concat "^" (regexp-quote mail-header-separator) "$"))
2924       (while (not (eobp))
2925         (when (not (looking-at "[ \t\n]"))
2926           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2927                             (char-after))))
2928         (forward-char 1)))
2929     sum))
2930
2931 (defun message-do-fcc ()
2932   "Process Fcc headers in the current buffer."
2933   (let ((case-fold-search t)
2934         (coding-system-for-write nnheader-message-coding-system-for-write)
2935         list file)
2936     (save-excursion
2937       (set-buffer (get-buffer-create " *message temp*"))
2938       (buffer-disable-undo (current-buffer))
2939       (erase-buffer)
2940       (insert-buffer-substring message-encoding-buffer)
2941       (save-restriction
2942         (message-narrow-to-headers)
2943         (while (setq file (message-fetch-field "fcc"))
2944           (push file list)
2945           (message-remove-header "fcc" nil t)))
2946       (goto-char (point-min))
2947       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2948       (replace-match "" t t)
2949       ;; Process FCC operations.
2950       (while list
2951         (setq file (pop list))
2952         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2953             ;; Pipe the article to the program in question.
2954             (call-process-region (point-min) (point-max) shell-file-name
2955                                  nil nil nil shell-command-switch
2956                                  (match-string 1 file))
2957           ;; Save the article.
2958           (setq file (expand-file-name file))
2959           (unless (file-exists-p (file-name-directory file))
2960             (make-directory (file-name-directory file) t))
2961           (if (and message-fcc-handler-function
2962                    (not (eq message-fcc-handler-function 'rmail-output)))
2963               (funcall message-fcc-handler-function file)
2964             (if (and (file-readable-p file) (mail-file-babyl-p file))
2965                 (rmail-output file 1 nil t)
2966               (let ((mail-use-rfc822 t))
2967                 (rmail-output file 1 t t))))))
2968
2969       (kill-buffer (current-buffer)))))
2970
2971 (defun message-output (filename)
2972   "Append this article to Unix/babyl mail file.."
2973   (if (and (file-readable-p filename)
2974            (mail-file-babyl-p filename))
2975       (gnus-output-to-rmail filename t)
2976     (gnus-output-to-mail filename t)))
2977
2978 (defun message-cleanup-headers ()
2979   "Do various automatic cleanups of the headers."
2980   ;; Remove empty lines in the header.
2981   (save-restriction
2982     (message-narrow-to-headers)
2983     ;; Remove blank lines.
2984     (while (re-search-forward "^[ \t]*\n" nil t)
2985       (replace-match "" t t))
2986
2987     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2988     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2989     ;; embedded line breaks.
2990     (goto-char (point-min))
2991     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2992       (save-restriction
2993         (narrow-to-region
2994          (point)
2995          (if (re-search-forward "^[^ \t]" nil t)
2996              (match-beginning 0)
2997            (forward-line 1)
2998            (point)))
2999         (goto-char (point-min))
3000         (while (re-search-forward "\n[ \t]+" nil t)
3001           (replace-match " " t t))      ;No line breaks (too confusing)
3002         (goto-char (point-min))
3003         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3004           (replace-match "," t t))
3005         (goto-char (point-min))
3006         ;; Remove trailing commas.
3007         (when (re-search-forward ",+$" nil t)
3008           (replace-match "" t t))))))
3009
3010 (defun message-make-date ()
3011   "Make a valid data header."
3012   (let ((now (current-time)))
3013     (timezone-make-date-arpa-standard
3014      (current-time-string now) (current-time-zone now))))
3015
3016 (defun message-make-message-id ()
3017   "Make a unique Message-ID."
3018   (concat "<" (message-unique-id)
3019           (let ((psubject (save-excursion (message-fetch-field "subject")))
3020                 (psupersedes
3021                  (save-excursion (message-fetch-field "supersedes"))))
3022             (if (or
3023                  (and message-reply-headers
3024                       (mail-header-references message-reply-headers)
3025                       (mail-header-subject message-reply-headers)
3026                       psubject
3027                       (mail-header-subject message-reply-headers)
3028                       (not (string=
3029                             (message-strip-subject-re
3030                              (mail-header-subject message-reply-headers))
3031                             (message-strip-subject-re psubject))))
3032                  (and psupersedes
3033                       (string-match "_-_@" psupersedes)))
3034                 "_-_" ""))
3035           "@" (message-make-fqdn) ">"))
3036
3037 (defvar message-unique-id-char nil)
3038
3039 ;; If you ever change this function, make sure the new version
3040 ;; cannot generate IDs that the old version could.
3041 ;; You might for example insert a "." somewhere (not next to another dot
3042 ;; or string boundary), or modify the "fsf" string.
3043 (defun message-unique-id ()
3044   ;; Don't use microseconds from (current-time), they may be unsupported.
3045   ;; Instead we use this randomly inited counter.
3046   (setq message-unique-id-char
3047         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3048            ;; (current-time) returns 16-bit ints,
3049            ;; and 2^16*25 just fits into 4 digits i base 36.
3050            (* 25 25)))
3051   (let ((tm (current-time)))
3052     (concat
3053      (if (memq system-type '(ms-dos emx vax-vms))
3054          (let ((user (downcase (user-login-name))))
3055            (while (string-match "[^a-z0-9_]" user)
3056              (aset user (match-beginning 0) ?_))
3057            user)
3058        (message-number-base36 (user-uid) -1))
3059      (message-number-base36 (+ (car   tm)
3060                                (lsh (% message-unique-id-char 25) 16)) 4)
3061      (message-number-base36 (+ (nth 1 tm)
3062                                (lsh (/ message-unique-id-char 25) 16)) 4)
3063      ;; Append the newsreader name, because while the generated
3064      ;; ID is unique to this newsreader, other newsreaders might
3065      ;; otherwise generate the same ID via another algorithm.
3066      ".fsf")))
3067
3068 (defun message-number-base36 (num len)
3069   (if (if (< len 0)
3070           (<= num 0)
3071         (= len 0))
3072       ""
3073     (concat (message-number-base36 (/ num 36) (1- len))
3074             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3075                                   (% num 36))))))
3076
3077 (defun message-make-organization ()
3078   "Make an Organization header."
3079   (let* ((organization
3080           (when message-user-organization
3081                 (if (message-functionp message-user-organization)
3082                     (funcall message-user-organization)
3083                   message-user-organization))))
3084     (save-excursion
3085       (message-set-work-buffer)
3086       (cond ((stringp organization)
3087              (insert organization))
3088             ((and (eq t organization)
3089                   message-user-organization-file
3090                   (file-exists-p message-user-organization-file))
3091              (insert-file-contents message-user-organization-file)))
3092       (goto-char (point-min))
3093       (while (re-search-forward "[\t\n]+" nil t)
3094         (replace-match "" t t))
3095       (unless (zerop (buffer-size))
3096         (buffer-string)))))
3097
3098 (defun message-make-lines ()
3099   "Count the number of lines and return numeric string."
3100   (save-excursion
3101     (save-restriction
3102       (widen)
3103       (goto-char (point-min))
3104       (re-search-forward
3105        (concat "^" (regexp-quote mail-header-separator) "$"))
3106       (forward-line 1)
3107       (int-to-string (count-lines (point) (point-max))))))
3108
3109 (defun message-make-in-reply-to ()
3110   "Return the In-Reply-To header for this message."
3111   (when message-reply-headers
3112     (let ((from (mail-header-from message-reply-headers))
3113           (date (mail-header-date message-reply-headers))
3114           (msg-id (mail-header-message-id message-reply-headers)))
3115       (when msg-id
3116         (concat msg-id
3117                 (when from
3118                   (let ((stop-pos
3119                          (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3120                     (concat " ("
3121                             (if (and stop-pos
3122                                      (not (zerop stop-pos)))
3123                                 (substring from 0 stop-pos) from)
3124                             "'s message of \""
3125                             (if (or (not date) (string= date ""))
3126                                 "(unknown date)" date)
3127                             "\")"))))))))
3128
3129 (defun message-make-distribution ()
3130   "Make a Distribution header."
3131   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3132     (cond ((message-functionp message-distribution-function)
3133            (funcall message-distribution-function))
3134           (t orig-distribution))))
3135
3136 (defun message-make-expires ()
3137   "Return an Expires header based on `message-expires'."
3138   (let ((current (current-time))
3139         (future (* 1.0 message-expires 60 60 24)))
3140     ;; Add the future to current.
3141     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3142     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3143     ;; Return the date in the future in UT.
3144     (timezone-make-date-arpa-standard
3145      (current-time-string current) (current-time-zone current) '(0 "UT"))))
3146
3147 (defun message-make-path ()
3148   "Return uucp path."
3149   (let ((login-name (user-login-name)))
3150     (cond ((null message-user-path)
3151            (concat (system-name) "!" login-name))
3152           ((stringp message-user-path)
3153            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3154            (concat message-user-path "!" login-name))
3155           (t login-name))))
3156
3157 (defun message-make-from ()
3158   "Make a From header."
3159   (let* ((style message-from-style)
3160          (login (message-make-address))
3161          (fullname
3162           (or (and (boundp 'user-full-name)
3163                    user-full-name)
3164               (user-full-name))))
3165     (when (string= fullname "&")
3166       (setq fullname (user-login-name)))
3167     (save-excursion
3168       (message-set-work-buffer)
3169       (cond
3170        ((or (null style)
3171             (equal fullname ""))
3172         (insert login))
3173        ((or (eq style 'angles)
3174             (and (not (eq style 'parens))
3175                  ;; Use angles if no quoting is needed, or if parens would
3176                  ;; need quoting too.
3177                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3178                      (let ((tmp (concat fullname nil)))
3179                        (while (string-match "([^()]*)" tmp)
3180                          (aset tmp (match-beginning 0) ?-)
3181                          (aset tmp (1- (match-end 0)) ?-))
3182                        (string-match "[\\()]" tmp)))))
3183         (insert fullname)
3184         (goto-char (point-min))
3185         ;; Look for a character that cannot appear unquoted
3186         ;; according to RFC 822.
3187         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3188           ;; Quote fullname, escaping specials.
3189           (goto-char (point-min))
3190           (insert "\"")
3191           (while (re-search-forward "[\"\\]" nil 1)
3192             (replace-match "\\\\\\&" t))
3193           (insert "\""))
3194         (insert " <" login ">"))
3195        (t                               ; 'parens or default
3196         (insert login " (")
3197         (let ((fullname-start (point)))
3198           (insert fullname)
3199           (goto-char fullname-start)
3200           ;; RFC 822 says \ and nonmatching parentheses
3201           ;; must be escaped in comments.
3202           ;; Escape every instance of ()\ ...
3203           (while (re-search-forward "[()\\]" nil 1)
3204             (replace-match "\\\\\\&" t))
3205           ;; ... then undo escaping of matching parentheses,
3206           ;; including matching nested parentheses.
3207           (goto-char fullname-start)
3208           (while (re-search-forward
3209                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3210                   nil 1)
3211             (replace-match "\\1(\\3)" t)
3212             (goto-char fullname-start)))
3213         (insert ")")))
3214       (buffer-string))))
3215
3216 (defun message-make-sender ()
3217   "Return the \"real\" user address.
3218 This function tries to ignore all user modifications, and
3219 give as trustworthy answer as possible."
3220   (concat (user-login-name) "@" (system-name)))
3221
3222 (defun message-make-address ()
3223   "Make the address of the user."
3224   (or (message-user-mail-address)
3225       (concat (user-login-name) "@" (message-make-domain))))
3226
3227 (defun message-user-mail-address ()
3228   "Return the pertinent part of `user-mail-address'."
3229   (when user-mail-address
3230     (if (string-match " " user-mail-address)
3231         (nth 1 (mail-extract-address-components user-mail-address))
3232       user-mail-address)))
3233
3234 (defun message-make-fqdn ()
3235   "Return user's fully qualified domain name."
3236   (let ((system-name (system-name))
3237         (user-mail (message-user-mail-address)))
3238     (cond
3239      ((string-match "[^.]\\.[^.]" system-name)
3240       ;; `system-name' returned the right result.
3241       system-name)
3242      ;; Try `mail-host-address'.
3243      ((and (boundp 'mail-host-address)
3244            (stringp mail-host-address)
3245            (string-match "\\." mail-host-address))
3246       mail-host-address)
3247      ;; We try `user-mail-address' as a backup.
3248      ((and user-mail
3249            (string-match "\\." user-mail)
3250            (string-match "@\\(.*\\)\\'" user-mail))
3251       (match-string 1 user-mail))
3252      ;; Default to this bogus thing.
3253      (t
3254       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3255
3256 (defun message-make-host-name ()
3257   "Return the name of the host."
3258   (let ((fqdn (message-make-fqdn)))
3259     (string-match "^[^.]+\\." fqdn)
3260     (substring fqdn 0 (1- (match-end 0)))))
3261
3262 (defun message-make-domain ()
3263   "Return the domain name."
3264   (or mail-host-address
3265       (message-make-fqdn)))
3266
3267 (defun message-make-user-agent ()
3268   "Return user-agent info."
3269   (if message-user-agent
3270       (save-excursion
3271         (goto-char (point-min))
3272         (let ((case-fold-search t)
3273               user-agent beg p end)
3274           (if (re-search-forward "^User-Agent:[ \t]*" nil t)
3275               (progn
3276                 (setq beg (match-beginning 0)
3277                       p (match-end 0)
3278                       end (std11-field-end)
3279                       user-agent (buffer-substring p end))
3280                 (delete-region beg (1+ end))
3281                 (concat message-user-agent " " user-agent)
3282                 )
3283             message-user-agent)))))
3284
3285 (defun message-generate-headers (headers)
3286   "Prepare article HEADERS.
3287 Headers already prepared in the buffer are not modified."
3288   (save-restriction
3289     (message-narrow-to-headers)
3290     (let* ((Date (message-make-date))
3291            (Message-ID (message-make-message-id))
3292            (Organization (message-make-organization))
3293            (From (message-make-from))
3294            (Path (message-make-path))
3295            (Subject nil)
3296            (Newsgroups nil)
3297            (In-Reply-To (message-make-in-reply-to))
3298            (To nil)
3299            (Distribution (message-make-distribution))
3300            (Lines (message-make-lines))
3301            (User-Agent (message-make-user-agent))
3302            (Expires (message-make-expires))
3303            (case-fold-search t)
3304            header value elem)
3305       ;; First we remove any old generated headers.
3306       (let ((headers message-deletable-headers))
3307         (unless (buffer-modified-p)
3308           (setq headers (delq 'Message-ID (copy-sequence headers))))
3309         (while headers
3310           (goto-char (point-min))
3311           (and (re-search-forward
3312                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3313                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3314                (message-delete-line))
3315           (pop headers)))
3316       ;; Go through all the required headers and see if they are in the
3317       ;; articles already.  If they are not, or are empty, they are
3318       ;; inserted automatically - except for Subject, Newsgroups and
3319       ;; Distribution.
3320       (while headers
3321         (goto-char (point-min))
3322         (setq elem (pop headers))
3323         (if (consp elem)
3324             (if (eq (car elem) 'optional)
3325                 (setq header (cdr elem))
3326               (setq header (car elem)))
3327           (setq header elem))
3328         (when (or (not (re-search-forward
3329                         (concat "^"
3330                                 (regexp-quote
3331                                  (downcase
3332                                   (if (stringp header)
3333                                       header
3334                                     (symbol-name header))))
3335                                 ":")
3336                         nil t))
3337                   (progn
3338                     ;; The header was found.  We insert a space after the
3339                     ;; colon, if there is none.
3340                     (if (eq (char-after) ? )
3341                         (forward-char 1)
3342                       (insert " "))
3343                     ;; Find out whether the header is empty...
3344                     (looking-at "[ \t]*$")))
3345           ;; So we find out what value we should insert.
3346           (setq value
3347                 (cond
3348                  ((and (consp elem) (eq (car elem) 'optional))
3349                   ;; This is an optional header.  If the cdr of this
3350                   ;; is something that is nil, then we do not insert
3351                   ;; this header.
3352                   (setq header (cdr elem))
3353                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3354                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3355                  ((consp elem)
3356                   ;; The element is a cons.  Either the cdr is a
3357                   ;; string to be inserted verbatim, or it is a
3358                   ;; function, and we insert the value returned from
3359                   ;; this function.
3360                   (or (and (stringp (cdr elem)) (cdr elem))
3361                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3362                  ((and (boundp header) (symbol-value header))
3363                   ;; The element is a symbol.  We insert the value
3364                   ;; of this symbol, if any.
3365                   (symbol-value header))
3366                  (t
3367                   ;; We couldn't generate a value for this header,
3368                   ;; so we just ask the user.
3369                   (read-from-minibuffer
3370                    (format "Empty header for %s; enter value: " header)))))
3371           ;; Finally insert the header.
3372           (when (and value
3373                      (not (equal value "")))
3374             (save-excursion
3375               (if (bolp)
3376                   (progn
3377                     ;; This header didn't exist, so we insert it.
3378                     (goto-char (point-max))
3379                     (insert (if (stringp header) header (symbol-name header))
3380                             ": " value "\n")
3381                     (forward-line -1))
3382                 ;; The value of this header was empty, so we clear
3383                 ;; totally and insert the new value.
3384                 (delete-region (point) (gnus-point-at-eol))
3385                 (insert value))
3386               ;; Add the deletable property to the headers that require it.
3387               (and (memq header message-deletable-headers)
3388                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3389                    (add-text-properties
3390                     (point) (match-end 0)
3391                     '(message-deletable t face italic) (current-buffer)))))))
3392       ;; Insert new Sender if the From is strange.
3393       (let ((from (message-fetch-field "from"))
3394             (sender (message-fetch-field "sender"))
3395             (secure-sender (message-make-sender)))
3396         (when (and from
3397                    (not (message-check-element 'sender))
3398                    (not (string=
3399                          (downcase
3400                           (cadr (mail-extract-address-components from)))
3401                          (downcase secure-sender)))
3402                    (or (null sender)
3403                        (not
3404                         (string=
3405                          (downcase
3406                           (cadr (mail-extract-address-components sender)))
3407                          (downcase secure-sender)))))
3408           (goto-char (point-min))
3409           ;; Rename any old Sender headers to Original-Sender.
3410           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3411             (beginning-of-line)
3412             (insert "Original-")
3413             (beginning-of-line))
3414           (when (or (message-news-p)
3415                     (string-match "@.+\\.." secure-sender))
3416             (insert "Sender: " secure-sender "\n")))))))
3417
3418 (defun message-insert-courtesy-copy ()
3419   "Insert a courtesy message in mail copies of combined messages."
3420   (let (newsgroups)
3421     (save-excursion
3422       (save-restriction
3423         (message-narrow-to-headers)
3424         (when (setq newsgroups (message-fetch-field "newsgroups"))
3425           (goto-char (point-max))
3426           (insert "Posted-To: " newsgroups "\n")))
3427       (forward-line 1)
3428       (when message-courtesy-message
3429         (cond
3430          ((string-match "%s" message-courtesy-message)
3431           (insert (format message-courtesy-message newsgroups)))
3432          (t
3433           (insert message-courtesy-message)))))))
3434
3435 ;;;
3436 ;;; Setting up a message buffer
3437 ;;;
3438
3439 (defun message-fill-address (header value)
3440   (save-restriction
3441     (narrow-to-region (point) (point))
3442     (insert (capitalize (symbol-name header))
3443             ": "
3444             (if (consp value) (car value) value)
3445             "\n")
3446     (narrow-to-region (point-min) (1- (point-max)))
3447     (let (quoted last)
3448       (goto-char (point-min))
3449       (while (not (eobp))
3450         (skip-chars-forward "^,\"" (point-max))
3451         (if (or (eq (char-after) ?,)
3452                 (eobp))
3453             (when (not quoted)
3454               (if (and (> (current-column) 78)
3455                        last)
3456                   (progn
3457                     (save-excursion
3458                       (goto-char last)
3459                       (insert "\n\t"))
3460                     (setq last (1+ (point))))
3461                 (setq last (1+ (point)))))
3462           (setq quoted (not quoted)))
3463         (unless (eobp)
3464           (forward-char 1))))
3465     (goto-char (point-max))
3466     (widen)
3467     (forward-line 1)))
3468
3469 (defun message-fill-references (header value)
3470   (insert (capitalize (symbol-name header))
3471           ": "
3472           (std11-fill-msg-id-list-string
3473            (if (consp value) (car value) value))
3474           "\n"))
3475
3476 (defun message-fill-header (header value)
3477   (let ((begin (point))
3478         (fill-column 990)
3479         (fill-prefix "\t"))
3480     (insert (capitalize (symbol-name header))
3481             ": "
3482             (if (consp value) (car value) value)
3483             "\n")
3484     (save-restriction
3485       (narrow-to-region begin (point))
3486       (fill-region-as-paragraph begin (point))
3487       ;; Tapdance around looong Message-IDs.
3488       (forward-line -1)
3489       (when (looking-at "[ \t]*$")
3490         (message-delete-line))
3491       (goto-char begin)
3492       (re-search-forward ":" nil t)
3493       (when (looking-at "\n[ \t]+")
3494         (replace-match " " t t))
3495       (goto-char (point-max)))))
3496
3497 (defun message-shorten-references (header references)
3498   "Limit REFERENCES to be shorter than 988 characters."
3499   (let ((max 988)
3500         (cut 4)
3501         refs)
3502     (nnheader-temp-write nil
3503       (insert references)
3504       (goto-char (point-min))
3505       (while (re-search-forward "<[^>]+>" nil t)
3506         (push (match-string 0) refs))
3507       (setq refs (nreverse refs))
3508       (while (> (length (mapconcat 'identity refs " ")) max)
3509         (when (< (length refs) (1+ cut))
3510           (decf cut))
3511         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3512     (insert (capitalize (symbol-name header)) ": "
3513             (mapconcat 'identity refs " ") "\n")))
3514
3515 (defun message-position-point ()
3516   "Move point to where the user probably wants to find it."
3517   (message-narrow-to-headers)
3518   (cond
3519    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3520     (search-backward ":" )
3521     (widen)
3522     (forward-char 1)
3523     (if (eq (char-after) ? )
3524         (forward-char 1)
3525       (insert " ")))
3526    (t
3527     (goto-char (point-max))
3528     (widen)
3529     (forward-line 1)
3530     (unless (looking-at "$")
3531       (forward-line 2)))
3532    (sit-for 0)))
3533
3534 (defun message-buffer-name (type &optional to group)
3535   "Return a new (unique) buffer name based on TYPE and TO."
3536   (cond
3537    ;; Check whether `message-generate-new-buffers' is a function,
3538    ;; and if so, call it.
3539    ((message-functionp message-generate-new-buffers)
3540     (funcall message-generate-new-buffers type to group))
3541    ;; Generate a new buffer name The Message Way.
3542    (message-generate-new-buffers
3543     (generate-new-buffer-name
3544      (concat "*" type
3545              (if to
3546                  (concat " to "
3547                          (or (car (mail-extract-address-components to))
3548                              to) "")
3549                "")
3550              (if (and group (not (string= group ""))) (concat " on " group) "")
3551              "*")))
3552    ;; Use standard name.
3553    (t
3554     (format "*%s message*" type))))
3555
3556 (defun message-pop-to-buffer (name)
3557   "Pop to buffer NAME, and warn if it already exists and is modified."
3558   (let ((pop-up-frames pop-up-frames)
3559         (special-display-buffer-names special-display-buffer-names)
3560         (special-display-regexps special-display-regexps)
3561         (same-window-buffer-names same-window-buffer-names)
3562         (same-window-regexps same-window-regexps)
3563         (buffer (get-buffer name))
3564         (cur (current-buffer)))
3565     (if (or (and (featurep 'xemacs)
3566                  (not (eq 'tty (device-type))))
3567             window-system
3568             (>= emacs-major-version 20))
3569         (when message-use-multi-frames
3570           (setq pop-up-frames t
3571                 special-display-buffer-names nil
3572                 special-display-regexps nil
3573                 same-window-buffer-names nil
3574                 same-window-regexps nil))
3575       (setq pop-up-frames nil))
3576     (if (and buffer
3577              (buffer-name buffer))
3578         (progn
3579           (set-buffer (pop-to-buffer buffer))
3580           (when (and (buffer-modified-p)
3581                      (not (y-or-n-p
3582                            "Message already being composed; erase? ")))
3583             (error "Message being composed")))
3584       (set-buffer (pop-to-buffer name)))
3585     (erase-buffer)
3586     (message-mode)
3587     (when pop-up-frames
3588       (make-local-variable 'message-original-frame)
3589       (setq message-original-frame (selected-frame)))))
3590
3591 (defun message-do-send-housekeeping ()
3592   "Kill old message buffers."
3593   ;; We might have sent this buffer already.  Delete it from the
3594   ;; list of buffers.
3595   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3596   (while (and message-max-buffers
3597               message-buffer-list
3598               (>= (length message-buffer-list) message-max-buffers))
3599     ;; Kill the oldest buffer -- unless it has been changed.
3600     (let ((buffer (pop message-buffer-list)))
3601       (when (and (buffer-name buffer)
3602                  (not (buffer-modified-p buffer)))
3603         (kill-buffer buffer))))
3604   ;; Rename the buffer.
3605   (if message-send-rename-function
3606       (funcall message-send-rename-function)
3607     (when (string-match "\\`\\*" (buffer-name))
3608       (rename-buffer
3609        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3610   ;; Push the current buffer onto the list.
3611   (when message-max-buffers
3612     (setq message-buffer-list
3613           (nconc message-buffer-list (list (current-buffer))))))
3614
3615 (defvar mc-modes-alist)
3616 (defun message-setup (headers &optional replybuffer actions)
3617   (when (and (boundp 'mc-modes-alist)
3618              (not (assq 'message-mode mc-modes-alist)))
3619     (push '(message-mode (encrypt . mc-encrypt-message)
3620                          (sign . mc-sign-message))
3621           mc-modes-alist))
3622   (when actions
3623     (setq message-send-actions actions))
3624   (setq message-reply-buffer
3625         (or (message-get-parameter 'reply-buffer)
3626             replybuffer))
3627   (goto-char (point-min))
3628   ;; Insert all the headers.
3629   (mail-header-format
3630    (let ((h headers)
3631          (alist message-header-format-alist))
3632      (while h
3633        (unless (assq (caar h) message-header-format-alist)
3634          (push (list (caar h)) alist))
3635        (pop h))
3636      alist)
3637    headers)
3638   (delete-region (point) (progn (forward-line -1) (point)))
3639   (when message-default-headers
3640     (insert message-default-headers)
3641     (or (bolp) (insert ?\n)))
3642   (put-text-property
3643    (point)
3644    (progn
3645      (insert mail-header-separator "\n")
3646      (1- (point)))
3647    'read-only nil)
3648   (forward-line -1)
3649   (when (message-news-p)
3650     (when message-default-news-headers
3651       (insert message-default-news-headers)
3652       (or (bolp) (insert ?\n)))
3653     (when message-generate-headers-first
3654       (message-generate-headers
3655        (delq 'Lines
3656              (delq 'Subject
3657                    (copy-sequence message-required-news-headers))))))
3658   (when (message-mail-p)
3659     (when message-default-mail-headers
3660       (insert message-default-mail-headers)
3661       (or (bolp) (insert ?\n)))
3662     (when message-generate-headers-first
3663       (message-generate-headers
3664        (delq 'Lines
3665              (delq 'Subject
3666                    (copy-sequence message-required-mail-headers))))))
3667   (run-hooks 'message-signature-setup-hook)
3668   (message-insert-signature)
3669   (save-restriction
3670     (message-narrow-to-headers)
3671     (run-hooks 'message-header-setup-hook))
3672   (set-buffer-modified-p nil)
3673   (setq buffer-undo-list nil)
3674   (add-to-list 'buffer-file-format 'message)
3675   (set-buffer-file-coding-system nnheader-message-coding-system-for-write)
3676   (run-hooks 'message-setup-hook)
3677   (message-position-point)
3678   (undo-boundary))
3679
3680 (defun message-set-auto-save-file-name ()
3681   "Associate the message buffer with a file in the drafts directory."
3682   (when message-auto-save-directory
3683     (if (gnus-alive-p)
3684         (setq message-draft-article
3685               (nndraft-request-associate-buffer "drafts"))
3686       (setq buffer-file-name (expand-file-name "*message*"
3687                                                message-auto-save-directory))
3688       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3689     (clear-visited-file-modtime)))
3690
3691 (defun message-disassociate-draft ()
3692   "Disassociate the message buffer from the drafts directory."
3693   (when message-draft-article
3694     (nndraft-request-expire-articles
3695      (list message-draft-article) "drafts" nil t)))
3696
3697 \f
3698
3699 ;;;
3700 ;;; Commands for interfacing with message
3701 ;;;
3702
3703 ;;;###autoload
3704 (defun message-mail (&optional to subject
3705                                other-headers continue switch-function
3706                                yank-action send-actions)
3707   "Start editing a mail message to be sent.
3708 OTHER-HEADERS is an alist of header/value pairs."
3709   (interactive)
3710   (let ((message-this-is-mail t))
3711     (message-pop-to-buffer (message-buffer-name "mail" to))
3712     (message-setup
3713      (nconc
3714       `((To . ,(or to "")) (Subject . ,(or subject "")))
3715       (when other-headers other-headers)))))
3716
3717 ;;;###autoload
3718 (defun message-news (&optional newsgroups subject)
3719   "Start editing a news article to be sent."
3720   (interactive)
3721   (let ((message-this-is-news t))
3722     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3723     (message-setup `((Newsgroups . ,(or newsgroups ""))
3724                      (Subject . ,(or subject ""))))))
3725
3726 ;;;###autoload
3727 (defun message-reply (&optional to-address wide)
3728   "Start editing a reply to the article in the current buffer."
3729   (interactive)
3730   (let ((cur (current-buffer))
3731         from subject date reply-to to cc
3732         references message-id follow-to
3733         (inhibit-point-motion-hooks t)
3734         mct never-mct gnus-warning in-reply-to)
3735     (save-restriction
3736       (message-narrow-to-head)
3737       ;; Allow customizations to have their say.
3738       (if (not wide)
3739           ;; This is a regular reply.
3740           (if (message-functionp message-reply-to-function)
3741               (setq follow-to (funcall message-reply-to-function)))
3742         ;; This is a followup.
3743         (if (message-functionp message-wide-reply-to-function)
3744             (save-excursion
3745               (setq follow-to
3746                     (funcall message-wide-reply-to-function)))))
3747       ;; Find all relevant headers we need.
3748       (setq from (message-fetch-field "from")
3749             date (message-fetch-field "date")
3750             subject (or (message-fetch-field "subject") "none")
3751             to (message-fetch-field "to")
3752             cc (message-fetch-field "cc")
3753             mct (message-fetch-field "mail-copies-to")
3754             reply-to (message-fetch-field "reply-to")
3755             references (message-fetch-field "references")
3756             message-id (message-fetch-field "message-id" t))
3757       ;; Get the references from "In-Reply-To" field if there were
3758       ;; no references and "In-Reply-To" field looks promising.
3759       (unless references
3760         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
3761                    (string-match "<[^>]+>" in-reply-to))
3762           (setq references (match-string 0 in-reply-to))))
3763       ;; Remove any (buggy) Re:'s that are present and make a
3764       ;; proper one.
3765       (when (string-match message-subject-re-regexp subject)
3766         (setq subject (substring subject (match-end 0))))
3767       (setq subject (concat "Re: " subject))
3768
3769       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3770                  (string-match "<[^>]+>" gnus-warning))
3771         (setq message-id (match-string 0 gnus-warning)))
3772
3773       ;; Handle special values of Mail-Copies-To.
3774       (when mct
3775         (cond ((equal (downcase mct) "never")
3776                (setq never-mct t)
3777                (setq mct nil))
3778               ((equal (downcase mct) "always")
3779                (setq mct (or reply-to from)))))
3780
3781       (unless follow-to
3782         (if (or (not wide)
3783                 to-address)
3784             (progn
3785               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3786               (when (and wide mct)
3787                 (push (cons 'Cc mct) follow-to)))
3788           (let (ccalist)
3789             (save-excursion
3790               (message-set-work-buffer)
3791               (unless never-mct
3792                 (insert (or reply-to from "")))
3793               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3794               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3795               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3796               (goto-char (point-min))
3797               (while (re-search-forward "[ \t]+" nil t)
3798                 (replace-match " " t t))
3799               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3800               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3801                         (erase-buffer)))
3802               (goto-char (point-min))
3803               ;; Perhaps Mail-Copies-To: never removed the only address?
3804               (when (eobp)
3805                 (insert (or reply-to from "")))
3806               (setq ccalist
3807                     (mapcar
3808                      (lambda (addr)
3809                        (cons (mail-strip-quoted-names addr) addr))
3810                      (message-tokenize-header (buffer-string))))
3811               (let ((s ccalist))
3812                 (while s
3813                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist))))
3814               (when (functionp message-mail-follow-up-address-checker)
3815                 (setq ccalist (funcall message-mail-follow-up-address-checker
3816                                        ccalist))))
3817             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3818             (when ccalist
3819               (let ((ccs (cons 'Cc (mapconcat
3820                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3821                 (when (string-match "^ +" (cdr ccs))
3822                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3823                 (push ccs follow-to))))))
3824       (widen))
3825
3826     (message-pop-to-buffer (message-buffer-name
3827                             (if wide "wide reply" "reply") from
3828                             (if wide to-address nil)))
3829
3830     (setq message-reply-headers
3831           (make-full-mail-header-from-decoded-header
3832            0 subject from date message-id references 0 0 ""))
3833
3834     (message-setup
3835      `((Subject . ,subject)
3836        ,@follow-to
3837        ,@(if (or references message-id)
3838              `((References . ,(concat (or references "") (and references " ")
3839                                       (or message-id ""))))
3840            nil))
3841      cur)))
3842
3843 ;;;###autoload
3844 (defun message-wide-reply (&optional to-address)
3845   "Make a \"wide\" reply to the message in the current buffer."
3846   (interactive)
3847   (message-reply to-address t))
3848
3849 ;;;###autoload
3850 (defun message-followup (&optional to-newsgroups)
3851   "Follow up to the message in the current buffer.
3852 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3853   (interactive)
3854   (let ((cur (current-buffer))
3855         from subject date reply-to mct
3856         references message-id follow-to
3857         (inhibit-point-motion-hooks t)
3858         (message-this-is-news t)
3859         followup-to distribution newsgroups gnus-warning posted-to)
3860     (save-restriction
3861       (narrow-to-region
3862        (goto-char (point-min))
3863        (if (search-forward "\n\n" nil t)
3864            (1- (point))
3865          (point-max)))
3866       (when (message-functionp message-followup-to-function)
3867         (setq follow-to
3868               (funcall message-followup-to-function)))
3869       (setq from (message-fetch-field "from")
3870             date (message-fetch-field "date")
3871             subject (or (message-fetch-field "subject") "none")
3872             references (message-fetch-field "references")
3873             message-id (message-fetch-field "message-id" t)
3874             followup-to (message-fetch-field "followup-to")
3875             newsgroups (message-fetch-field "newsgroups")
3876             posted-to (message-fetch-field "posted-to")
3877             reply-to (message-fetch-field "reply-to")
3878             distribution (message-fetch-field "distribution")
3879             mct (message-fetch-field "mail-copies-to"))
3880       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3881                  (string-match "<[^>]+>" gnus-warning))
3882         (setq message-id (match-string 0 gnus-warning)))
3883       ;; Remove bogus distribution.
3884       (when (and (stringp distribution)
3885                  (let ((case-fold-search t))
3886                    (string-match "world" distribution)))
3887         (setq distribution nil))
3888       ;; Remove any (buggy) Re:'s that are present and make a
3889       ;; proper one.
3890       (when (string-match message-subject-re-regexp subject)
3891         (setq subject (substring subject (match-end 0))))
3892       (setq subject (concat "Re: " subject))
3893       (widen))
3894
3895     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3896
3897     (message-setup
3898      `((Subject . ,subject)
3899        ,@(cond
3900           (to-newsgroups
3901            (list (cons 'Newsgroups to-newsgroups)))
3902           (follow-to follow-to)
3903           ((and followup-to message-use-followup-to)
3904            (list
3905             (cond
3906              ((equal (downcase followup-to) "poster")
3907               (if (or (eq message-use-followup-to 'use)
3908                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3909 You should normally obey the Followup-To: header.
3910
3911 `Followup-To: poster' sends your response via e-mail instead of news.
3912
3913 A typical situation where `Followup-To: poster' is used is when the poster
3914 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3915                   (progn
3916                     (setq message-this-is-news nil)
3917                     (cons 'To (or reply-to from "")))
3918                 (cons 'Newsgroups newsgroups)))
3919              (t
3920               (if (or (equal followup-to newsgroups)
3921                       (not (eq message-use-followup-to 'ask))
3922                       (message-y-or-n-p
3923                        (concat "Obey Followup-To: " followup-to "? ") t "\
3924 You should normally obey the Followup-To: header.
3925
3926         `Followup-To: " followup-to "'
3927 directs your response to " (if (string-match "," followup-to)
3928                                "the specified newsgroups"
3929                              "that newsgroup only") ".
3930
3931 If a message is posted to several newsgroups, Followup-To is often
3932 used to direct the following discussion to one newsgroup only,
3933 because discussions that are spread over several newsgroup tend to
3934 be fragmented and very difficult to follow.
3935
3936 Also, some source/announcement newsgroups are not indented for discussion;
3937 responses here are directed to other newsgroups."))
3938                   (cons 'Newsgroups followup-to)
3939                 (cons 'Newsgroups newsgroups))))))
3940           (posted-to
3941            `((Newsgroups . ,posted-to)))
3942           (t
3943            `((Newsgroups . ,newsgroups))))
3944        ,@(and distribution (list (cons 'Distribution distribution)))
3945        ,@(if (or references message-id)
3946              `((References . ,(concat (or references "") (and references " ")
3947                                       (or message-id "")))))
3948        ,@(when (and mct
3949                     (not (equal (downcase mct) "never")))
3950            (list (cons 'Cc (if (equal (downcase mct) "always")
3951                                (or reply-to from "")
3952                              mct)))))
3953
3954      cur)
3955
3956     (setq message-reply-headers
3957           (make-full-mail-header-from-decoded-header
3958            0 subject from date message-id references 0 0 ""))))
3959
3960
3961 ;;;###autoload
3962 (defun message-cancel-news ()
3963   "Cancel an article you posted."
3964   (interactive)
3965   (unless (message-news-p)
3966     (error "This is not a news article; canceling is impossible"))
3967   (when (yes-or-no-p "Do you really want to cancel this article? ")
3968     (let (from newsgroups message-id distribution buf sender)
3969       (save-excursion
3970         ;; Get header info. from original article.
3971         (save-restriction
3972           (message-narrow-to-head)
3973           (setq from (message-fetch-field "from")
3974                 sender (message-fetch-field "sender")
3975                 newsgroups (message-fetch-field "newsgroups")
3976                 message-id (message-fetch-field "message-id" t)
3977                 distribution (message-fetch-field "distribution")))
3978         ;; Make sure that this article was written by the user.
3979         (unless (or (and sender
3980                          (string-equal
3981                           (downcase sender)
3982                           (downcase (message-make-sender))))
3983                     (string-equal
3984                      (downcase (cadr (mail-extract-address-components from)))
3985                      (downcase (cadr (mail-extract-address-components
3986                                       (message-make-from))))))
3987           (error "This article is not yours"))
3988         ;; Make control message.
3989         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3990         (buffer-disable-undo (current-buffer))
3991         (erase-buffer)
3992         (insert "Newsgroups: " newsgroups "\n"
3993                 "From: " (message-make-from) "\n"
3994                 "Subject: cmsg cancel " message-id "\n"
3995                 "Control: cancel " message-id "\n"
3996                 (if distribution
3997                     (concat "Distribution: " distribution "\n")
3998                   "")
3999                 mail-header-separator "\n"
4000                 message-cancel-message)
4001         (message "Canceling your article...")
4002         (if (let ((message-syntax-checks
4003                    'dont-check-for-anything-just-trust-me)
4004                   (message-encoding-buffer (current-buffer))
4005                   (message-edit-buffer (current-buffer)))
4006               (message-send-news))
4007             (message "Canceling your article...done"))
4008         (kill-buffer buf)))))
4009
4010 (defun message-supersede-setup-for-mime-edit ()
4011   (set (make-local-variable 'message-setup-hook) nil)
4012   (mime-edit-again))
4013
4014 ;;;###autoload
4015 (defun message-supersede ()
4016   "Start composing a message to supersede the current message.
4017 This is done simply by taking the old article and adding a Supersedes
4018 header line with the old Message-ID."
4019   (interactive)
4020   (let ((cur (current-buffer))
4021         (sender (message-fetch-field "sender"))
4022         (from (message-fetch-field "from")))
4023     ;; Check whether the user owns the article that is to be superseded.
4024     (unless (or (and sender
4025                      (string-equal
4026                       (downcase sender)
4027                       (downcase (message-make-sender))))
4028                 (string-equal
4029                  (downcase (cadr (mail-extract-address-components from)))
4030                  (downcase (cadr (mail-extract-address-components
4031                                   (message-make-from))))))
4032       (error "This article is not yours"))
4033     ;; Get a normal message buffer.
4034     (message-pop-to-buffer (message-buffer-name "supersede"))
4035     (insert-buffer-substring cur)
4036     (message-narrow-to-head)
4037     ;; Remove unwanted headers.
4038     (when message-ignored-supersedes-headers
4039       (message-remove-header message-ignored-supersedes-headers t))
4040     (goto-char (point-min))
4041     (if (not (re-search-forward "^Message-ID: " nil t))
4042         (error "No Message-ID in this article")
4043       (replace-match "Supersedes: " t t))
4044     (goto-char (point-max))
4045     (insert mail-header-separator)
4046     (widen)
4047     (when message-supersede-setup-function
4048       (funcall message-supersede-setup-function))
4049     (run-hooks 'message-supersede-setup-hook)
4050     (goto-char (point-min))
4051     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
4052
4053 ;;;###autoload
4054 (defun message-recover ()
4055   "Reread contents of current buffer from its last auto-save file."
4056   (interactive)
4057   (let ((file-name (make-auto-save-file-name)))
4058     (cond ((save-window-excursion
4059              (if (not (eq system-type 'vax-vms))
4060                  (with-output-to-temp-buffer "*Directory*"
4061                    (buffer-disable-undo standard-output)
4062                    (let ((default-directory "/"))
4063                      (call-process
4064                       "ls" nil standard-output nil "-l" file-name))))
4065              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4066            (let ((buffer-read-only nil))
4067              (erase-buffer)
4068              (insert-file-contents file-name nil)))
4069           (t (error "message-recover cancelled")))))
4070
4071 ;;; Washing Subject:
4072
4073 (defun message-wash-subject (subject)
4074   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4075   (nnheader-temp-write nil
4076     (insert-string subject)
4077     (goto-char (point-min))
4078     ;; strip Re/Fwd stuff off the beginning
4079     (while (re-search-forward
4080             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4081       (replace-match ""))
4082
4083     ;; and gnus-style forwards [foo@bar.com] subject
4084     (goto-char (point-min))
4085     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4086       (replace-match ""))
4087
4088     ;; and off the end
4089     (goto-char (point-max))
4090     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4091       (replace-match ""))
4092
4093     ;; and finally, any whitespace that was left-over
4094     (goto-char (point-min))
4095     (while (re-search-forward "^[ \t]+" nil t)
4096       (replace-match ""))
4097     (goto-char (point-max))
4098     (while (re-search-backward "[ \t]+$" nil t)
4099       (replace-match ""))
4100
4101     (buffer-string)))
4102     
4103 ;;; Forwarding messages.
4104
4105 (defun message-forward-subject-author-subject (subject)
4106   "Generate a subject for a forwarded message.
4107 The form is: [Source] Subject, where if the original message was mail,
4108 Source is the sender, and if the original message was news, Source is
4109 the list of newsgroups is was posted to."
4110   (concat "["
4111           (or (message-fetch-field
4112                (if (message-news-p) "newsgroups" "from"))
4113               "(nowhere)")
4114           "] " subject))
4115
4116 (defun message-forward-subject-fwd (subject)
4117   "Generate a subject for a forwarded message.
4118 The form is: Fwd: Subject, where Subject is the original subject of
4119 the message."
4120   (concat "Fwd: " subject))
4121
4122 (defun message-make-forward-subject ()
4123   "Return a Subject header suitable for the message in the current buffer."
4124   (save-excursion
4125     (save-restriction
4126       (current-buffer)
4127       (message-narrow-to-head)
4128       (let ((funcs message-make-forward-subject-function)
4129             (subject (message-fetch-field "Subject")))
4130         (setq subject
4131               (if subject
4132                   (if message-wash-forwarded-subjects
4133                       (message-wash-subject
4134                        (nnheader-decode-subject subject))
4135                     (nnheader-decode-subject subject))
4136                 "(none)"))
4137         ;; Make sure funcs is a list.
4138         (and funcs
4139              (not (listp funcs))
4140              (setq funcs (list funcs)))
4141         ;; Apply funcs in order, passing subject generated by previous
4142         ;; func to the next one.
4143         (while funcs
4144           (when (message-functionp (car funcs))
4145             (setq subject (funcall (car funcs) subject)))
4146           (setq funcs (cdr funcs)))
4147         subject))))
4148
4149 ;;;###autoload
4150 (defun message-forward (&optional news)
4151   "Forward the current message via mail.
4152 Optional NEWS will use news to forward instead of mail."
4153   (interactive "P")
4154   (let ((cur (current-buffer))
4155         (subject (message-make-forward-subject))
4156         art-beg)
4157     (if news (message-news nil subject) (message-mail nil subject))
4158     ;; Put point where we want it before inserting the forwarded
4159     ;; message.
4160     (if message-signature-before-forwarded-message
4161         (goto-char (point-max))
4162       (message-goto-body))
4163     ;; Make sure we're at the start of the line.
4164     (unless (eolp)
4165       (insert "\n"))
4166     ;; Narrow to the area we are to insert.
4167     (narrow-to-region (point) (point))
4168     ;; Insert the separators and the forwarded buffer.
4169     (insert message-forward-start-separator)
4170     (setq art-beg (point))
4171     (insert-buffer-substring cur)
4172     (goto-char (point-max))
4173     (insert message-forward-end-separator)
4174     (set-text-properties (point-min) (point-max) nil)
4175     ;; Remove all unwanted headers.
4176     (goto-char art-beg)
4177     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
4178                                   (1- (point))
4179                                 (point)))
4180     (goto-char (point-min))
4181     (message-remove-header message-included-forward-headers t nil t)
4182     (widen)
4183     (message-position-point)))
4184
4185 ;;;###autoload
4186 (defun message-resend (address)
4187   "Resend the current article to ADDRESS."
4188   (interactive "sResend message to: ")
4189   (message "Resending message to %s..." address)
4190   (save-excursion
4191     (let ((cur (current-buffer))
4192           beg)
4193       ;; We first set up a normal mail buffer.
4194       (set-buffer (get-buffer-create " *message resend*"))
4195       (buffer-disable-undo (current-buffer))
4196       (erase-buffer)
4197       ;; avoid to turn-on-mime-edit
4198       (let (message-setup-hook)
4199         (message-setup `((To . ,address)))
4200         )
4201       ;; Insert our usual headers.
4202       (message-generate-headers '(From Date To))
4203       (message-narrow-to-headers)
4204       ;; Rename them all to "Resent-*".
4205       (while (re-search-forward "^[A-Za-z]" nil t)
4206         (forward-char -1)
4207         (insert "Resent-"))
4208       (widen)
4209       (forward-line)
4210       (delete-region (point) (point-max))
4211       (setq beg (point))
4212       ;; Insert the message to be resent.
4213       (insert-buffer-substring cur)
4214       (goto-char (point-min))
4215       (search-forward "\n\n")
4216       (forward-char -1)
4217       (save-restriction
4218         (narrow-to-region beg (point))
4219         (message-remove-header message-ignored-resent-headers t)
4220         (goto-char (point-max)))
4221       (insert mail-header-separator)
4222       ;; Rename all old ("Also-")Resent headers.
4223       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4224         (beginning-of-line)
4225         (insert "Also-"))
4226       ;; Quote any "From " lines at the beginning.
4227       (goto-char beg)
4228       (when (looking-at "From ")
4229         (replace-match "X-From-Line: "))
4230       ;; Send it.
4231       (let ((message-encoding-buffer (current-buffer))
4232             (message-edit-buffer (current-buffer)))
4233         (message-send-mail))
4234       (kill-buffer (current-buffer)))
4235     (message "Resending message to %s...done" address)))
4236
4237 (defun message-bounce-setup-for-mime-edit ()
4238   (set (make-local-variable 'message-setup-hook) nil)
4239   (mime-edit-again))
4240
4241 ;;;###autoload
4242 (defun message-bounce ()
4243   "Re-mail the current message.
4244 This only makes sense if the current message is a bounce message than
4245 contains some mail you have written which has been bounced back to
4246 you."
4247   (interactive)
4248   (let ((cur (current-buffer))
4249         boundary)
4250     (message-pop-to-buffer (message-buffer-name "bounce"))
4251     (insert-buffer-substring cur)
4252     (undo-boundary)
4253     (message-narrow-to-head)
4254     (if (and (message-fetch-field "MIME-Version")
4255              (setq boundary (message-fetch-field "Content-Type")))
4256         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
4257             (setq boundary (concat (match-string 1 boundary) " *\n"
4258                                    "Content-Type: message/rfc822"))
4259           (setq boundary nil)))
4260     (widen)
4261     (goto-char (point-min))
4262     (search-forward "\n\n" nil t)
4263     (or (and boundary
4264              (re-search-forward boundary nil t)
4265              (forward-line 2))
4266         (and (re-search-forward message-unsent-separator nil t)
4267              (forward-line 1))
4268         (re-search-forward "^Return-Path:.*\n" nil t))
4269     ;; We remove everything before the bounced mail.
4270     (delete-region
4271      (point-min)
4272      (if (re-search-forward "^[^ \n\t]+:" nil t)
4273          (match-beginning 0)
4274        (point)))
4275     (save-restriction
4276       (message-narrow-to-head)
4277       (message-remove-header message-ignored-bounced-headers t)
4278       (goto-char (point-max))
4279       (insert mail-header-separator))
4280     (when message-bounce-setup-function
4281       (funcall message-bounce-setup-function))
4282     (run-hooks 'message-bounce-setup-hook)
4283     (message-position-point)))
4284
4285 ;;;
4286 ;;; Interactive entry points for new message buffers.
4287 ;;;
4288
4289 ;;;###autoload
4290 (defun message-mail-other-window (&optional to subject)
4291   "Like `message-mail' command, but display mail buffer in another window."
4292   (interactive)
4293   (let ((pop-up-windows t)
4294         (special-display-buffer-names nil)
4295         (special-display-regexps nil)
4296         (same-window-buffer-names nil)
4297         (same-window-regexps nil))
4298     (message-pop-to-buffer (message-buffer-name "mail" to)))
4299   (let ((message-this-is-mail t))
4300     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4301
4302 ;;;###autoload
4303 (defun message-mail-other-frame (&optional to subject)
4304   "Like `message-mail' command, but display mail buffer in another frame."
4305   (interactive)
4306   (let ((pop-up-frames t)
4307         (special-display-buffer-names nil)
4308         (special-display-regexps nil)
4309         (same-window-buffer-names nil)
4310         (same-window-regexps nil))
4311     (message-pop-to-buffer (message-buffer-name "mail" to)))
4312   (let ((message-this-is-mail t))
4313     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4314
4315 ;;;###autoload
4316 (defun message-news-other-window (&optional newsgroups subject)
4317   "Start editing a news article to be sent."
4318   (interactive)
4319   (let ((pop-up-windows t)
4320         (special-display-buffer-names nil)
4321         (special-display-regexps nil)
4322         (same-window-buffer-names nil)
4323         (same-window-regexps nil))
4324     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4325   (let ((message-this-is-news t))
4326     (message-setup `((Newsgroups . ,(or newsgroups ""))
4327                      (Subject . ,(or subject ""))))))
4328
4329 ;;;###autoload
4330 (defun message-news-other-frame (&optional newsgroups subject)
4331   "Start editing a news article to be sent."
4332   (interactive)
4333   (let ((pop-up-frames t)
4334         (special-display-buffer-names nil)
4335         (special-display-regexps nil)
4336         (same-window-buffer-names nil)
4337         (same-window-regexps nil))
4338     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4339   (let ((message-this-is-news t))
4340     (message-setup `((Newsgroups . ,(or newsgroups ""))
4341                      (Subject . ,(or subject ""))))))
4342
4343 ;;; underline.el
4344
4345 ;; This code should be moved to underline.el (from which it is stolen).
4346
4347 ;;;###autoload
4348 (defun bold-region (start end)
4349   "Bold all nonblank characters in the region.
4350 Works by overstriking characters.
4351 Called from program, takes two arguments START and END
4352 which specify the range to operate on."
4353   (interactive "r")
4354   (save-excursion
4355     (let ((end1 (make-marker)))
4356       (move-marker end1 (max start end))
4357       (goto-char (min start end))
4358       (while (< (point) end1)
4359         (or (looking-at "[_\^@- ]")
4360             (insert (char-after) "\b"))
4361         (forward-char 1)))))
4362
4363 ;;;###autoload
4364 (defun unbold-region (start end)
4365   "Remove all boldness (overstruck characters) in the region.
4366 Called from program, takes two arguments START and END
4367 which specify the range to operate on."
4368   (interactive "r")
4369   (save-excursion
4370     (let ((end1 (make-marker)))
4371       (move-marker end1 (max start end))
4372       (goto-char (min start end))
4373       (while (re-search-forward "\b" end1 t)
4374         (if (eq (char-after) (char-after (- (point) 2)))
4375             (delete-char -2))))))
4376
4377 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4378
4379 ;; Support for toolbar
4380 (when (string-match "XEmacs\\|Lucid" emacs-version)
4381   (require 'messagexmas))
4382
4383 ;;; Group name completion.
4384
4385 (defvar message-newgroups-header-regexp
4386   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4387   "Regexp that match headers that lists groups.")
4388
4389 (defun message-tab ()
4390   "Expand group names in Newsgroups and Followup-To headers.
4391 Do a `tab-to-tab-stop' if not in those headers."
4392   (interactive)
4393   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4394         (mail-abbrev-in-expansion-header-p))
4395       (message-expand-group)
4396     (tab-to-tab-stop)))
4397
4398 (defvar gnus-active-hashtb)
4399 (defun message-expand-group ()
4400   "Expand the group name under point."
4401   (let* ((b (save-excursion
4402               (save-restriction
4403                 (narrow-to-region
4404                  (save-excursion
4405                    (beginning-of-line)
4406                    (skip-chars-forward "^:")
4407                    (1+ (point)))
4408                  (point))
4409                 (skip-chars-backward "^, \t\n") (point))))
4410          (completion-ignore-case t)
4411          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4412                                             (point))))
4413          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4414          (completions (all-completions string hashtb))
4415          comp)
4416     (delete-region b (point))
4417     (cond
4418      ((= (length completions) 1)
4419       (if (string= (car completions) string)
4420           (progn
4421             (insert string)
4422             (message "Only matching group"))
4423         (insert (car completions))))
4424      ((and (setq comp (try-completion string hashtb))
4425            (not (string= comp string)))
4426       (insert comp))
4427      (t
4428       (insert string)
4429       (if (not comp)
4430           (message "No matching groups")
4431         (save-selected-window
4432           (pop-to-buffer "*Completions*")
4433           (buffer-disable-undo (current-buffer))
4434           (let ((buffer-read-only nil))
4435             (erase-buffer)
4436             (let ((standard-output (current-buffer)))
4437               (display-completion-list (sort completions 'string<)))
4438             (goto-char (point-min))
4439             (delete-region (point) (progn (forward-line 3) (point))))))))))
4440
4441 ;;; Help stuff.
4442
4443 (defun message-talkative-question (ask question show &rest text)
4444   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4445 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4446 The following arguments may contain lists of values."
4447   (if (and show
4448            (setq text (message-flatten-list text)))
4449       (save-window-excursion
4450         (save-excursion
4451           (with-output-to-temp-buffer " *MESSAGE information message*"
4452             (set-buffer " *MESSAGE information message*")
4453             (mapcar 'princ text)
4454             (goto-char (point-min))))
4455         (funcall ask question))
4456     (funcall ask question)))
4457
4458 (defun message-flatten-list (list)
4459   "Return a new, flat list that contains all elements of LIST.
4460
4461 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4462 => (1 2 3 4 5 6 7)"
4463   (cond ((consp list)
4464          (apply 'append (mapcar 'message-flatten-list list)))
4465         (list
4466          (list list))))
4467
4468 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4469   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4470 Then clone the local variables and values from the old buffer to the
4471 new one, cloning only the locals having a substring matching the
4472 regexp varstr."
4473   (let ((oldbuf (current-buffer)))
4474     (save-excursion
4475       (set-buffer (generate-new-buffer name))
4476       (message-clone-locals oldbuf)
4477       (current-buffer))))
4478
4479 (defun message-clone-locals (buffer)
4480   "Clone the local variables from BUFFER to the current buffer."
4481   (let ((locals (save-excursion
4482                   (set-buffer buffer)
4483                   (buffer-local-variables)))
4484         (regexp "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
4485     (mapcar
4486      (lambda (local)
4487        (when (and (consp local)
4488                   (car local)
4489                   (string-match regexp (symbol-name (car local))))
4490          (ignore-errors
4491            (set (make-local-variable (car local))
4492                 (cdr local)))))
4493      locals)))
4494
4495 ;; @ For `message-mail-follow-up-address-checker'.
4496
4497 (defcustom message-mailing-list-address-list nil
4498   "*Regexp matching addresses that are mailing lists.
4499 It must be a simple regexp string or a list of regexp strings.
4500 This variable is used by \`message-check-mailing-list-with-address-list\'."
4501   :group 'message-mail
4502   :type '(repeat regexp))
4503
4504 (defun message-check-mailing-list-with-address-list (alist)
4505   (let ((s alist)
4506         (regexp (if (stringp message-mailing-list-address-list)
4507                     message-mailing-list-address-list
4508                   (mapconcat
4509                    (lambda (x)
4510                      x)
4511                    message-mailing-list-address-list
4512                    "\\|")))
4513         address non-mailing-list mailing-list)
4514     (while (setq address (car (pop s)))
4515       (if (string-match regexp address)
4516           (setq mailing-list t)
4517         (setq non-mailing-list
4518               (append non-mailing-list (list address)))))
4519     (if (or (not non-mailing-list)
4520             (not mailing-list)
4521             (not (y-or-n-p "Do you want to remove private address? ")))
4522         alist
4523       (setq s non-mailing-list)
4524       (while s
4525         (setq alist (delq (assoc (pop s) alist) alist)))
4526       alist)
4527     ))
4528
4529 (defcustom message-mailing-list-address-p nil
4530   "*The function return t if address is a mailing list.
4531 It must be function, and interface is (ADDRESS).
4532 ADDRESS is a string of mail address.
4533 This variable is used by \`message-check-mailing-list-with-function\'."
4534   :group 'message-mail
4535   :type 'function)
4536
4537 (defun message-check-mailing-list-with-function (alist)
4538   (let ((s alist)
4539         address non-mailing-list mailing-list)
4540     (while (setq address (car (pop s)))
4541       (if (funcall message-mailing-list-address-p address)
4542           (setq mailing-list t)
4543         (setq non-mailing-list
4544               (append non-mailing-list (list address)))))
4545     (if (or (not non-mailing-list)
4546             (not mailing-list)
4547             (not (y-or-n-p "Do you want to remove private address? ")))
4548         alist
4549       (setq s non-mailing-list)
4550       (while s
4551         (setq alist (delq (assoc (pop s) alist) alist)))
4552       alist)
4553     ))
4554
4555 ;;; @ Encode buffer.
4556 ;;;
4557
4558 (defun message-maybe-encode ()
4559   (when message-mime-mode
4560     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
4561     (let ((pgp-processing (with-current-buffer message-edit-buffer
4562                             mime-edit-pgp-processing)))
4563       (setq mime-edit-pgp-processing pgp-processing))
4564     (run-hooks 'mime-edit-translate-hook)
4565     (if (catch 'mime-edit-error
4566           (save-excursion
4567             (mime-edit-pgp-enclose-buffer)
4568             (mime-edit-translate-body)
4569             ))
4570         (error "Translation error!")
4571       ))
4572   (end-of-invisible)
4573   (run-hooks 'mime-edit-exit-hook)
4574   )
4575
4576 ;;; @ for saving buffer
4577 ;;;
4578
4579 (defvar message-save-encoder 'message-mime-save-encoder)
4580
4581 (defun message-save-formatter (start end &optional orig-buf)
4582   "Format message, when save message buffer. [message.el]"
4583   (save-restriction
4584     (narrow-to-region start end)
4585     (and message-save-encoder
4586          (funcall message-save-encoder orig-buf))
4587     (goto-char start)
4588     (and (search-forward (concat "\n" mail-header-separator "\n") nil t)
4589          (replace-match "\n\n"))
4590     ))
4591
4592 (set-alist 'format-alist
4593            'message
4594            '("Message."
4595              "1\\(^\\)"
4596              nil
4597              message-save-formatter
4598              t nil))
4599
4600 ;;; @ for MIME Edit mode
4601 ;;;
4602
4603 (defun message-mime-insert-article (&optional message)
4604   (interactive)
4605   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4606         (message-reply-buffer
4607          (message-get-parameter-with-eval 'original-buffer))
4608         (start (point)))
4609     (message-yank-original nil)
4610     (save-excursion
4611       (narrow-to-region (goto-char start)
4612                         (if (search-forward "\n\n" nil t)
4613                             (1- (point))
4614                           (point-max)))
4615       (goto-char (point-min))
4616       (message-remove-header message-included-forward-headers t nil t)
4617       (widen))))
4618
4619 (set-alist 'mime-edit-message-inserter-alist
4620            'message-mode (function message-mime-insert-article))
4621
4622 (defun message-mime-save-encoder (orig-buf)
4623   (when (with-current-buffer orig-buf mime-edit-mode-flag)
4624     (mime-edit-translate-body)
4625     (mime-edit-translate-header)
4626     ))
4627
4628 (defun message-mime-after-save-hook ()
4629   (set-buffer-file-coding-system nnheader-message-coding-system-for-write)
4630   (set-buffer-modified-p nil)
4631   )
4632
4633 (defun message-mime-setup ()
4634   (turn-on-mime-edit)
4635   (make-local-hook 'after-save-hook)
4636   (add-hook 'after-save-hook 'message-mime-after-save-hook nil t)
4637   )
4638
4639 (run-hooks 'message-load-hook)
4640
4641 (provide 'message)
4642
4643 ;;; message.el ends here