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