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