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