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