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