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