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