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