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